blob: 1f2376e638fe04e855441768f669e2ead323b20e [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;
74 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
75 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
76 };
Bob Wilson84945262009-05-12 17:09:30 +000077
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// CPUsers - Keep track of all of the machine instructions that use various
79 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000080 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000081
Evan Chengc99ef082007-02-09 20:54:44 +000082 /// CPEntry - One per constant pool entry, keeping the machine instruction
83 /// pointer, the constpool index, and the number of CPUser's which
84 /// reference this entry.
85 struct CPEntry {
86 MachineInstr *CPEMI;
87 unsigned CPI;
88 unsigned RefCount;
89 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
90 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
91 };
92
93 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000094 /// instructions. For each original constpool index (i.e. those that
95 /// existed upon entry to this pass), it keeps a vector of entries.
96 /// Original elements are cloned as we go along; the clones are
97 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000098 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +000099
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000100 /// ImmBranch - One per immediate branch, keeping the machine instruction
101 /// pointer, conditional or unconditional, the max displacement,
102 /// and (if isCond is true) the corresponding unconditional branch
103 /// opcode.
104 struct ImmBranch {
105 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000106 unsigned MaxDisp : 31;
107 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000108 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000109 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
110 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000111 };
112
Evan Cheng2706f972007-05-16 05:14:06 +0000113 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000114 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000115 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000116
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000117 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
118 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000119 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000120
121 /// HasFarJump - True if any far jump instruction has been emitted during
122 /// the branch fix up pass.
123 bool HasFarJump;
124
Evan Chenga8e29892007-01-19 07:51:42 +0000125 const TargetInstrInfo *TII;
Dale Johannesen8593e412007-04-29 19:19:30 +0000126 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000127 bool isThumb;
David Goodwinf1daf7d2009-07-08 23:10:31 +0000128 bool isThumb1Only;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000129 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000130 public:
Devang Patel19974732007-05-03 01:11:54 +0000131 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000132 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000133
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 }
Bob Wilson84945262009-05-12 17:09:30 +0000139
Evan Chenga8e29892007-01-19 07:51:42 +0000140 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);
Bob Wilson84945262009-05-12 17:09:30 +0000151 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000152 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000153 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000154 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();
Bob Wilson84945262009-05-12 17:09:30 +0000160 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000161 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) {
Bob Wilson84945262009-05-12 17:09:30 +0000202 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000203 " 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();
Bob Wilson84945262009-05-12 17:09:30 +0000215
Evan Chenga8e29892007-01-19 07:51:42 +0000216 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();
David Goodwinf1daf7d2009-07-08 23:10:31 +0000219 isThumb1Only = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000220 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000221
222 HasFarJump = false;
223
Evan Chenga8e29892007-01-19 07:51:42 +0000224 // Renumber all of the machine basic blocks in the function, guaranteeing that
225 // the numbers agree with the position of the block in the function.
226 Fn.RenumberBlocks();
227
Bob Wilson84945262009-05-12 17:09:30 +0000228 /// Thumb functions containing constant pools get 2-byte alignment.
229 /// This is so we can keep exact track of where the alignment padding goes.
230 /// Set default.
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000231 AFI->setAlign(isThumb ? 1U : 2U);
232
Evan Chenga8e29892007-01-19 07:51:42 +0000233 // Perform the initial placement of the constant pool entries. To start with,
234 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000235 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000236 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000237 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000238 if (isThumb)
239 AFI->setAlign(2U);
240 }
Bob Wilson84945262009-05-12 17:09:30 +0000241
Evan Chenga8e29892007-01-19 07:51:42 +0000242 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000243 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000244
Evan Chenga8e29892007-01-19 07:51:42 +0000245 // Do the initial scan of the function, building up information about the
246 // sizes of each block, the location of all the water, and finding all of the
247 // constant pool users.
248 InitialFunctionScan(Fn, CPEMIs);
249 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000250
Evan Chenged884f32007-04-03 23:39:48 +0000251 /// Remove dead constant pool entries.
252 RemoveUnusedCPEntries();
253
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000254 // Iteratively place constant pool entries and fix up branches until there
255 // is no change.
256 bool MadeChange = false;
257 while (true) {
258 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000259 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000260 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000261 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000262 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000263 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000264 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000265 if (!Change)
266 break;
267 MadeChange = true;
268 }
Evan Chenged884f32007-04-03 23:39:48 +0000269
Dale Johannesen8593e412007-04-29 19:19:30 +0000270 // After a while, this might be made debug-only, but it is not expensive.
271 verify(Fn);
272
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000273 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
274 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000275 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000276 MadeChange |= UndoLRSpillRestore();
277
Evan Chenga8e29892007-01-19 07:51:42 +0000278 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000279 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000280 WaterList.clear();
281 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000282 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000283 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000284 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000285
286 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000287}
288
289/// DoInitialPlacement - Perform the initial placement of the constant pool
290/// entries. To start with, we put them all at the end of the function.
291void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilson84945262009-05-12 17:09:30 +0000292 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000293 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000294 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
295 Fn.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000296
Evan Chenga8e29892007-01-19 07:51:42 +0000297 // Add all of the constants from the constant pool to the end block, use an
298 // identity mapping of CPI's to CPE's.
299 const std::vector<MachineConstantPoolEntry> &CPs =
300 Fn.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000301
Evan Chenga8e29892007-01-19 07:51:42 +0000302 const TargetData &TD = *Fn.getTarget().getTargetData();
303 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000304 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000305 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
306 // we would have to pad them out or something so that instructions stay
307 // aligned.
308 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
309 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000310 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000311 .addImm(i).addConstantPoolIndex(i).addImm(Size);
312 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000313
314 // Add a new CPEntry, but no corresponding CPUser yet.
315 std::vector<CPEntry> CPEs;
316 CPEs.push_back(CPEntry(CPEMI, i));
317 CPEntries.push_back(CPEs);
318 NumCPEs++;
319 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000320 }
321}
322
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000323/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000324/// into the block immediately after it.
325static bool BBHasFallthrough(MachineBasicBlock *MBB) {
326 // Get the next machine basic block in the function.
327 MachineFunction::iterator MBBI = MBB;
328 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
329 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000330
Evan Chenga8e29892007-01-19 07:51:42 +0000331 MachineBasicBlock *NextBB = next(MBBI);
332 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
333 E = MBB->succ_end(); I != E; ++I)
334 if (*I == NextBB)
335 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000336
Evan Chenga8e29892007-01-19 07:51:42 +0000337 return false;
338}
339
Evan Chengc99ef082007-02-09 20:54:44 +0000340/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
341/// look up the corresponding CPEntry.
342ARMConstantIslands::CPEntry
343*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
344 const MachineInstr *CPEMI) {
345 std::vector<CPEntry> &CPEs = CPEntries[CPI];
346 // Number of entries per constpool index should be small, just do a
347 // linear search.
348 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
349 if (CPEs[i].CPEMI == CPEMI)
350 return &CPEs[i];
351 }
352 return NULL;
353}
354
Evan Chenga8e29892007-01-19 07:51:42 +0000355/// InitialFunctionScan - Do the initial scan of the function, building up
356/// information about the sizes of each block, the location of all the water,
357/// and finding all of the constant pool users.
358void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000359 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000360 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000361 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
362 MBBI != E; ++MBBI) {
363 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000364
Evan Chenga8e29892007-01-19 07:51:42 +0000365 // If this block doesn't fall through into the next MBB, then this is
366 // 'water' that a constant pool island could be placed.
367 if (!BBHasFallthrough(&MBB))
368 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000369
Evan Chenga8e29892007-01-19 07:51:42 +0000370 unsigned MBBSize = 0;
371 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
372 I != E; ++I) {
373 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000374 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000375
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000376 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000377 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000378 bool isCond = false;
379 unsigned Bits = 0;
380 unsigned Scale = 1;
381 int UOpc = Opc;
382 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000383 case ARM::tBR_JTr:
David Goodwin5e47a9a2009-06-30 18:04:13 +0000384 case ARM::t2BR_JTr:
David Goodwinc9a59b52009-06-30 19:50:22 +0000385 case ARM::t2BR_JTm:
386 case ARM::t2BR_JTadd:
Dale Johannesen8593e412007-04-29 19:19:30 +0000387 // A Thumb table jump may involve padding; for the offsets to
388 // be right, functions containing these must be 4-byte aligned.
389 AFI->setAlign(2U);
390 if ((Offset+MBBSize)%4 != 0)
391 MBBSize += 2; // padding
392 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000393 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000394 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000395 case ARM::Bcc:
396 isCond = true;
397 UOpc = ARM::B;
398 // Fallthrough
399 case ARM::B:
400 Bits = 24;
401 Scale = 4;
402 break;
403 case ARM::tBcc:
404 isCond = true;
405 UOpc = ARM::tB;
406 Bits = 8;
407 Scale = 2;
408 break;
409 case ARM::tB:
410 Bits = 11;
411 Scale = 2;
412 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000413 case ARM::t2Bcc:
414 isCond = true;
415 UOpc = ARM::t2B;
416 Bits = 20;
417 Scale = 2;
418 break;
419 case ARM::t2B:
420 Bits = 24;
421 Scale = 2;
422 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000423 }
Evan Chengb43216e2007-02-01 10:16:15 +0000424
425 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000426 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000427 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000428 }
429
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000430 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
431 PushPopMIs.push_back(I);
432
Evan Chenga8e29892007-01-19 07:51:42 +0000433 // Scan the instructions for constant pool operands.
434 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000435 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000436 // We found one. The addressing mode tells us the max displacement
437 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000438
Evan Chenga8e29892007-01-19 07:51:42 +0000439 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000440 unsigned Bits = 0;
441 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000442 unsigned TSFlags = I->getDesc().TSFlags;
Evan Chenga8e29892007-01-19 07:51:42 +0000443 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilson84945262009-05-12 17:09:30 +0000444 default:
Evan Chenga8e29892007-01-19 07:51:42 +0000445 // Constant pool entries can reach anything.
446 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
447 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000448 if (I->getOpcode() == ARM::tLEApcrel) {
449 Bits = 8; // Taking the address of a CP entry.
450 break;
451 }
Torok Edwinc25e7582009-07-11 20:10:48 +0000452 LLVM_UNREACHABLE("Unknown addressing mode for CP reference!");
Evan Chenga8e29892007-01-19 07:51:42 +0000453 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000454 Bits = 8;
455 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000456 break;
457 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000458 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000459 break;
460 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000461 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000462 break;
463 // addrmode4 has no immediate offset.
464 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000465 Bits = 8;
466 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000467 break;
Bob Wilson8b024a52009-07-01 23:16:05 +0000468 // addrmode6 has no immediate offset.
Evan Cheng055b0312009-06-29 07:51:04 +0000469 case ARMII::AddrModeT1_1:
Evan Chengb43216e2007-02-01 10:16:15 +0000470 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000471 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000472 case ARMII::AddrModeT1_2:
Evan Chengb43216e2007-02-01 10:16:15 +0000473 Bits = 5;
474 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000475 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000476 case ARMII::AddrModeT1_4:
Evan Chengb43216e2007-02-01 10:16:15 +0000477 Bits = 5;
478 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000479 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000480 case ARMII::AddrModeT1_s:
Evan Chengb43216e2007-02-01 10:16:15 +0000481 Bits = 8;
482 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000483 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000484 case ARMII::AddrModeT2_pc:
485 Bits = 12; // +-offset_12
486 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000487 }
Evan Chengb43216e2007-02-01 10:16:15 +0000488
Evan Chenga8e29892007-01-19 07:51:42 +0000489 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000490 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000491 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000492 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000493 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000494
495 // Increment corresponding CPEntry reference count.
496 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
497 assert(CPE && "Cannot find a corresponding CPEntry!");
498 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000499
Evan Chenga8e29892007-01-19 07:51:42 +0000500 // Instructions can only use one CP entry, don't bother scanning the
501 // rest of the operands.
502 break;
503 }
504 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000505
Dale Johannesen8593e412007-04-29 19:19:30 +0000506 // In thumb mode, if this block is a constpool island, we may need padding
507 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000508 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000509 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000510 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
511 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000512 MBBSize += 2;
513
Evan Chenga8e29892007-01-19 07:51:42 +0000514 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000515 BBOffsets.push_back(Offset);
516 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000517 }
518}
519
Evan Chenga8e29892007-01-19 07:51:42 +0000520/// GetOffsetOf - Return the current offset of the specified machine instruction
521/// from the start of the function. This offset changes as stuff is moved
522/// around inside the function.
523unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
524 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000525
Evan Chenga8e29892007-01-19 07:51:42 +0000526 // The offset is composed of two things: the sum of the sizes of all MBB's
527 // before this instruction's block, and the offset from the start of the block
528 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000529 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000530
Dale Johannesen8593e412007-04-29 19:19:30 +0000531 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
532 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000533 if (isThumb &&
534 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000535 Offset%4 != 0)
536 Offset += 2;
537
Evan Chenga8e29892007-01-19 07:51:42 +0000538 // Sum instructions before MI in MBB.
539 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
540 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
541 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000542 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000543 }
544}
545
546/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
547/// ID.
548static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
549 const MachineBasicBlock *RHS) {
550 return LHS->getNumber() < RHS->getNumber();
551}
552
553/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
554/// machine function, it upsets all of the block numbers. Renumber the blocks
555/// and update the arrays that parallel this numbering.
556void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
557 // Renumber the MBB's to keep them consequtive.
558 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000559
Evan Chenga8e29892007-01-19 07:51:42 +0000560 // Insert a size into BBSizes to align it properly with the (newly
561 // renumbered) block numbers.
562 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000563
564 // Likewise for BBOffsets.
565 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000566
567 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000568 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000569 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000570 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
571 CompareMBBNumbers);
572 WaterList.insert(IP, NewBB);
573}
574
575
576/// Split the basic block containing MI into two blocks, which are joined by
577/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000578/// account for this change and returns the newly created block.
579MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000580 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000581 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000582
583 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000584 MachineBasicBlock *NewBB =
585 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000586 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000587 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000588
Evan Chenga8e29892007-01-19 07:51:42 +0000589 // Splice the instructions starting with MI over to NewBB.
590 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000591
Evan Chenga8e29892007-01-19 07:51:42 +0000592 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000593 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000594 // There doesn't seem to be meaningful DebugInfo available; this doesn't
595 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000596 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
597 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000598 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000599
Evan Chenga8e29892007-01-19 07:51:42 +0000600 // Update the CFG. All succs of OrigBB are now succs of NewBB.
601 while (!OrigBB->succ_empty()) {
602 MachineBasicBlock *Succ = *OrigBB->succ_begin();
603 OrigBB->removeSuccessor(Succ);
604 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000605
Evan Chenga8e29892007-01-19 07:51:42 +0000606 // This pass should be run after register allocation, so there should be no
607 // PHI nodes to update.
608 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
609 && "PHI nodes should be eliminated by now!");
610 }
Bob Wilson84945262009-05-12 17:09:30 +0000611
Evan Chenga8e29892007-01-19 07:51:42 +0000612 // OrigBB branches to NewBB.
613 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000614
Evan Chenga8e29892007-01-19 07:51:42 +0000615 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000616 // This is almost the same as UpdateForInsertedWaterBlock, except that
617 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000618 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000619
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000620 // Insert a size into BBSizes to align it properly with the (newly
621 // renumbered) block numbers.
622 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000623
Dale Johannesen99c49a42007-02-25 00:47:03 +0000624 // Likewise for BBOffsets.
625 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
626
Bob Wilson84945262009-05-12 17:09:30 +0000627 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000628 // available water after it (but not if it's already there, which happens
629 // when splitting before a conditional branch that is followed by an
630 // unconditional branch - in that case we want to insert NewBB).
631 std::vector<MachineBasicBlock*>::iterator IP =
632 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
633 CompareMBBNumbers);
634 MachineBasicBlock* WaterBB = *IP;
635 if (WaterBB == OrigBB)
636 WaterList.insert(next(IP), NewBB);
637 else
638 WaterList.insert(IP, OrigBB);
639
Dale Johannesen8593e412007-04-29 19:19:30 +0000640 // Figure out how large the first NewMBB is. (It cannot
641 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000642 unsigned NewBBSize = 0;
643 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
644 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000645 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000646
Dale Johannesen99c49a42007-02-25 00:47:03 +0000647 unsigned OrigBBI = OrigBB->getNumber();
648 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000649 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000650 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000651
Evan Chenga8e29892007-01-19 07:51:42 +0000652 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000653 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000654 unsigned delta = isThumb ? 2 : 4;
655 BBSizes[OrigBBI] -= NewBBSize - delta;
656
657 // ...and adjust BBOffsets for NewBB accordingly.
658 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
659
660 // All BBOffsets following these blocks must be modified.
661 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000662
663 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000664}
665
Dale Johannesen8593e412007-04-29 19:19:30 +0000666/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000667/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000668/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000669bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000670 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilson84945262009-05-12 17:09:30 +0000671 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
672 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000673 // Effectively, the valid range of displacements is 2 bytes smaller for such
674 // references.
675 if (isThumb && UserOffset%4 !=0)
676 UserOffset -= 2;
677 // CPEs will be rounded up to a multiple of 4.
678 if (isThumb && TrialOffset%4 != 0)
679 TrialOffset += 2;
680
Dale Johannesen99c49a42007-02-25 00:47:03 +0000681 if (UserOffset <= TrialOffset) {
682 // User before the Trial.
683 if (TrialOffset-UserOffset <= MaxDisp)
684 return true;
685 } else if (NegativeOK) {
686 if (UserOffset-TrialOffset <= MaxDisp)
687 return true;
688 }
689 return false;
690}
691
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000692/// WaterIsInRange - Returns true if a CPE placed after the specified
693/// Water (a basic block) will be in range for the specific MI.
694
695bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000696 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000697{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000698 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000699 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilson84945262009-05-12 17:09:30 +0000700 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000701 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000702
Dale Johannesend959aa42007-04-02 20:31:06 +0000703 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000704 // the offset of the instruction. (Currently applies only to ARM, so
705 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000706 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000707 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000708
Dale Johannesen99c49a42007-02-25 00:47:03 +0000709 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000710}
711
712/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000713/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000714bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
715 MachineInstr *CPEMI,
716 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000717 unsigned CPEOffset = GetOffsetOf(CPEMI);
718 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000719
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000720 if (DoDump) {
721 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
722 << " max delta=" << MaxDisp
723 << " insn address=" << UserOffset
724 << " CPE address=" << CPEOffset
725 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
726 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000727
Dale Johannesen99c49a42007-02-25 00:47:03 +0000728 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000729}
730
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000731#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000732/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
733/// unconditionally branches to its only successor.
734static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
735 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
736 return false;
737
738 MachineBasicBlock *Succ = *MBB->succ_begin();
739 MachineBasicBlock *Pred = *MBB->pred_begin();
740 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000741 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
742 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000743 return PredMI->getOperand(0).getMBB() == Succ;
744 return false;
745}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000746#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000747
Bob Wilson84945262009-05-12 17:09:30 +0000748void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000749 int delta) {
750 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
751 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000752 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000753 // If some existing blocks have padding, adjust the padding as needed, a
754 // bit tricky. delta can be negative so don't use % on that.
755 if (isThumb) {
756 MachineBasicBlock *MBB = MBBI;
757 if (!MBB->empty()) {
758 // Constant pool entries require padding.
759 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
760 unsigned oldOffset = BBOffsets[i] - delta;
761 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
762 // add new padding
763 BBSizes[i] += 2;
764 delta += 2;
765 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
766 // remove existing padding
767 BBSizes[i] -=2;
768 delta -= 2;
769 }
770 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000771 // Thumb jump tables require padding. They should be at the end;
772 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000773 MachineInstr *ThumbJTMI = NULL;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000774 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
David Goodwinc9a59b52009-06-30 19:50:22 +0000775 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
776 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
777 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
Dale Johannesen8593e412007-04-29 19:19:30 +0000778 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000779 if (ThumbJTMI) {
780 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
781 unsigned oldMIOffset = newMIOffset - delta;
782 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
783 // remove existing padding
784 BBSizes[i] -= 2;
785 delta -= 2;
786 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
787 // add new padding
788 BBSizes[i] += 2;
789 delta += 2;
790 }
791 }
792 if (delta==0)
793 return;
794 }
795 MBBI = next(MBBI);
796 }
797 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000798}
799
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000800/// DecrementOldEntry - find the constant pool entry with index CPI
801/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000802/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000803/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000804
Evan Chenged884f32007-04-03 23:39:48 +0000805bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000806 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000807 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
808 assert(CPE && "Unexpected!");
809 if (--CPE->RefCount == 0) {
810 RemoveDeadCPEMI(CPEMI);
811 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000812 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000813 return true;
814 }
815 return false;
816}
817
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000818/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
819/// if not, see if an in-range clone of the CPE is in range, and if so,
820/// change the data structures so the user references the clone. Returns:
821/// 0 = no existing entry found
822/// 1 = entry found, and there were no code insertions or deletions
823/// 2 = entry found, and there were code insertions or deletions
824int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
825{
826 MachineInstr *UserMI = U.MI;
827 MachineInstr *CPEMI = U.CPEMI;
828
829 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000830 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
831 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000832 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000833 }
834
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000835 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000836 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000837 std::vector<CPEntry> &CPEs = CPEntries[CPI];
838 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
839 // We already tried this one
840 if (CPEs[i].CPEMI == CPEMI)
841 continue;
842 // Removing CPEs can leave empty entries, skip
843 if (CPEs[i].CPEMI == NULL)
844 continue;
845 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
846 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
847 // Point the CPUser node to the replacement
848 U.CPEMI = CPEs[i].CPEMI;
849 // Change the CPI in the instruction operand to refer to the clone.
850 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000851 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000852 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000853 break;
854 }
855 // Adjust the refcount of the clone...
856 CPEs[i].RefCount++;
857 // ...and the original. If we didn't remove the old entry, none of the
858 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000859 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000860 }
861 }
862 return 0;
863}
864
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000865/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
866/// the specific unconditional branch instruction.
867static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000868 switch (Opc) {
869 case ARM::tB:
870 return ((1<<10)-1)*2;
871 case ARM::t2B:
872 return ((1<<23)-1)*2;
873 default:
874 break;
875 }
876
877 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000878}
879
Dale Johannesen8593e412007-04-29 19:19:30 +0000880/// AcceptWater - Small amount of common code factored out of the following.
881
Bob Wilson84945262009-05-12 17:09:30 +0000882MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000883 std::vector<MachineBasicBlock*>::iterator IP) {
884 DOUT << "found water in range\n";
885 // Remove the original WaterList entry; we want subsequent
886 // insertions in this vicinity to go after the one we're
887 // about to insert. This considerably reduces the number
888 // of times we have to move the same CPE more than once.
889 WaterList.erase(IP);
890 // CPE goes before following block (NewMBB).
891 return next(MachineFunction::iterator(WaterBB));
892}
893
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000894/// LookForWater - look for an existing entry in the WaterList in which
895/// we can place the CPE referenced from U so it's within range of U's MI.
896/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000897/// is set to the WaterList entry.
898/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
899/// water that will not introduce padding to water that will; within each
900/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000901
902bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000903 MachineBasicBlock** NewMBB) {
904 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
905 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000906 if (!WaterList.empty()) {
907 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
908 B = WaterList.begin();; --IP) {
909 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000910 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000911 if (isThumb &&
Bob Wilson84945262009-05-12 17:09:30 +0000912 (BBOffsets[WaterBB->getNumber()] +
Dale Johannesen8593e412007-04-29 19:19:30 +0000913 BBSizes[WaterBB->getNumber()])%4 != 0) {
914 // This is valid Water, but would introduce padding. Remember
915 // it in case we don't find any Water that doesn't do this.
916 if (!WaterBBThatWouldPad) {
917 WaterBBThatWouldPad = WaterBB;
918 IPThatWouldPad = IP;
919 }
920 } else {
921 *NewMBB = AcceptWater(WaterBB, IP);
922 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000923 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000924 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000925 if (IP == B)
926 break;
927 }
928 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000929 if (isThumb && WaterBBThatWouldPad) {
930 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
931 return true;
932 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000933 return false;
934}
935
Bob Wilson84945262009-05-12 17:09:30 +0000936/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000937/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
938/// block is used if in range, and the conditional branch munged so control
939/// flow is correct. Otherwise the block is split to create a hole with an
940/// unconditional branch around it. In either case *NewMBB is set to a
941/// block following which the new island can be inserted (the WaterList
942/// is not adjusted).
943
Bob Wilson84945262009-05-12 17:09:30 +0000944void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000945 unsigned UserOffset, MachineBasicBlock** NewMBB) {
946 CPUser &U = CPUsers[CPUserIndex];
947 MachineInstr *UserMI = U.MI;
948 MachineInstr *CPEMI = U.CPEMI;
949 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000950 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000951 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000952 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000953
954 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000955 // is within range, make new water there. (The addition below is
956 // for the unconditional branch we will be adding: 4 bytes on ARM,
957 // 2 on Thumb. Possible Thumb alignment padding is allowed for
958 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000959 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000960 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000961 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000962 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
963 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000964 DOUT << "Split at end of block\n";
965 if (&UserMBB->back() == UserMI)
966 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
967 *NewMBB = next(MachineFunction::iterator(UserMBB));
968 // Add an unconditional branch from UserMBB to fallthrough block.
969 // Record it for branch lengthening; this new branch will not get out of
970 // range, but if the preceding conditional branch is out of range, the
971 // targets will be exchanged, and the altered branch may be out of
972 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +0000973 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000974 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
975 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000976 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000977 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000978 MaxDisp, false, UncondBr));
979 int delta = isThumb ? 2 : 4;
980 BBSizes[UserMBB->getNumber()] += delta;
981 AdjustBBOffsetsAfter(UserMBB, delta);
982 } else {
983 // What a big block. Find a place within the block to split it.
984 // This is a little tricky on Thumb since instructions are 2 bytes
985 // and constant pool entries are 4 bytes: if instruction I references
986 // island CPE, and instruction I+1 references CPE', it will
987 // not work well to put CPE as far forward as possible, since then
988 // CPE' cannot immediately follow it (that location is 2 bytes
989 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000990 // a new island. So, we make a first guess, then walk through the
991 // instructions between the one currently being looked at and the
992 // possible insertion point, and make sure any other instructions
993 // that reference CPEs will be able to use the same island area;
994 // if not, we back up the insertion point.
995
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000996 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000997 // inserting (allows for long branch on Thumb). Alignment of the
998 // island is handled inside OffsetIsInRange.
999 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001000 // This could point off the end of the block if we've already got
1001 // constant pool entries following this block; only the last one is
1002 // in the water list. Back past any possible branches (allow for a
1003 // conditional and a maximally long unconditional).
1004 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001005 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001006 (isThumb ? 6 : 8);
1007 unsigned EndInsertOffset = BaseInsertOffset +
1008 CPEMI->getOperand(2).getImm();
1009 MachineBasicBlock::iterator MI = UserMI;
1010 ++MI;
1011 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001012 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001013 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001014 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001015 MI = next(MI)) {
1016 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilson84945262009-05-12 17:09:30 +00001017 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1019 BaseInsertOffset -= (isThumb ? 2 : 4);
1020 EndInsertOffset -= (isThumb ? 2 : 4);
1021 }
1022 // This is overly conservative, as we don't account for CPEMIs
1023 // being reused within the block, but it doesn't matter much.
1024 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1025 CPUIndex++;
1026 }
1027 }
1028 DOUT << "Split in middle of big block\n";
1029 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1030 }
1031}
1032
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001033/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001034/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001035/// place in-range. Return true if we changed any addresses (thus must run
1036/// another pass of branch lengthening), false otherwise.
Bob Wilson84945262009-05-12 17:09:30 +00001037bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1038 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001039 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001040 MachineInstr *UserMI = U.MI;
1041 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001042 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001043 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001044 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001045 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001046 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001047 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001048
Evan Cheng185ea1e2007-04-27 18:27:13 +00001049 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1050 // second instruction.
1051 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001052 UserOffset += 2;
Bob Wilson84945262009-05-12 17:09:30 +00001053
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001054 // See if the current entry is within range, or there is a clone of it
1055 // in range.
1056 int result = LookForExistingCPEntry(U, UserOffset);
1057 if (result==1) return false;
1058 else if (result==2) return true;
1059
1060 // No existing clone of this CPE is within range.
1061 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001062 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001063
1064 // Look for water where we can place this CPE. We look for the farthest one
1065 // away that will work. Forward references only for now (although later
1066 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001067
Dale Johannesen8593e412007-04-29 19:19:30 +00001068 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001069 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001070 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001071 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001072 }
1073
1074 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001075 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1076 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001077
1078 // Update internal data structures to account for the newly inserted MBB.
1079 UpdateForInsertedWaterBlock(NewIsland);
1080
1081 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001082 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001083
1084 // Now that we have an island to add the CPE to, clone the original CPE and
1085 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001086 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1087 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001088 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001089 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001090 NumCPEs++;
1091
Dale Johannesen8593e412007-04-29 19:19:30 +00001092 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001093 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001094 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001095 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001096 // Increase the size of the island block to account for the new entry.
1097 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001098 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001099
Evan Chenga8e29892007-01-19 07:51:42 +00001100 // Finally, change the CPI in the instruction operand to be ID.
1101 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001102 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001103 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001104 break;
1105 }
Bob Wilson84945262009-05-12 17:09:30 +00001106
Evan Chengc99ef082007-02-09 20:54:44 +00001107 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001108
Evan Chenga8e29892007-01-19 07:51:42 +00001109 return true;
1110}
1111
Evan Chenged884f32007-04-03 23:39:48 +00001112/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1113/// sizes and offsets of impacted basic blocks.
1114void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1115 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001116 unsigned Size = CPEMI->getOperand(2).getImm();
1117 CPEMI->eraseFromParent();
1118 BBSizes[CPEBB->getNumber()] -= Size;
1119 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001120 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001121 // In thumb mode, the size of island may be padded by two to compensate for
1122 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001123 // empty, so fix this.
1124 // All succeeding offsets have the current size value added in, fix this.
1125 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001126 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001127 BBSizes[CPEBB->getNumber()] = 0;
1128 }
Evan Chenged884f32007-04-03 23:39:48 +00001129 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001130 AdjustBBOffsetsAfter(CPEBB, -Size);
1131 // An island has only one predecessor BB and one successor BB. Check if
1132 // this BB's predecessor jumps directly to this BB's successor. This
1133 // shouldn't happen currently.
1134 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1135 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001136}
1137
1138/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1139/// are zero.
1140bool ARMConstantIslands::RemoveUnusedCPEntries() {
1141 unsigned MadeChange = false;
1142 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1143 std::vector<CPEntry> &CPEs = CPEntries[i];
1144 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1145 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1146 RemoveDeadCPEMI(CPEs[j].CPEMI);
1147 CPEs[j].CPEMI = NULL;
1148 MadeChange = true;
1149 }
1150 }
Bob Wilson84945262009-05-12 17:09:30 +00001151 }
Evan Chenged884f32007-04-03 23:39:48 +00001152 return MadeChange;
1153}
1154
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001155/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001156/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001157bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1158 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001159 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001160 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001161 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001162
Evan Chengc99ef082007-02-09 20:54:44 +00001163 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1164 << " from BB#" << MI->getParent()->getNumber()
1165 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001166 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1167 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001168
Dale Johannesen8593e412007-04-29 19:19:30 +00001169 if (BrOffset <= DestOffset) {
1170 // Branch before the Dest.
1171 if (DestOffset-BrOffset <= MaxDisp)
1172 return true;
1173 } else {
1174 if (BrOffset-DestOffset <= MaxDisp)
1175 return true;
1176 }
1177 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001178}
1179
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001180/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1181/// away to fit in its displacement field.
1182bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001183 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001184 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001185
Evan Chengc0dbec72007-01-31 19:57:44 +00001186 // Check to see if the DestBB is already in-range.
1187 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001188 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001189
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001190 if (!Br.isCond)
1191 return FixUpUnconditionalBr(Fn, Br);
1192 return FixUpConditionalBr(Fn, Br);
1193}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001194
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001195/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1196/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001197/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001198/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001199bool
1200ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1201 MachineInstr *MI = Br.MI;
1202 MachineBasicBlock *MBB = MI->getParent();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001203 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001204
1205 // Use BL to implement far jump.
1206 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001207 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001208 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001209 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001210 HasFarJump = true;
1211 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001212
Evan Chengc99ef082007-02-09 20:54:44 +00001213 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001214
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001215 return true;
1216}
1217
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001218/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001219/// far away to fit in its displacement field. It is converted to an inverse
1220/// conditional branch + an unconditional branch to the destination.
1221bool
1222ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1223 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001224 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001225
Bob Wilson39bf0512009-05-12 17:35:29 +00001226 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001227 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001228 // blt L1
1229 // =>
1230 // bge L2
1231 // b L1
1232 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001233 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001234 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001235 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001236
1237 // If the branch is at the end of its MBB and that has a fall-through block,
1238 // direct the updated conditional branch to the fall-through block. Otherwise,
1239 // split the MBB before the next instruction.
1240 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001241 MachineInstr *BMI = &MBB->back();
1242 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001243
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001244 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001245 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001246 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001247 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001248 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001249 // condition and swap destinations:
1250 // beq L1
1251 // b L2
1252 // =>
1253 // bne L2
1254 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001255 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001256 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001257 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001258 BMI->getOperand(0).setMBB(DestBB);
1259 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001260 MI->getOperand(1).setImm(CC);
1261 return true;
1262 }
1263 }
1264 }
1265
1266 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001267 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001268 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001269 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001270 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001271 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001272 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1273 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001274 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001275 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001276 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001277 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001278
Evan Chengc99ef082007-02-09 20:54:44 +00001279 DOUT << " Insert B to BB#" << DestBB->getNumber()
1280 << " also invert condition and change dest. to BB#"
1281 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001282
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001283 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001284 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001285 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1286 TII->get(MI->getOpcode()))
1287 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001288 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001289 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001290 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001291 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001292 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001293 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001294
1295 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001296 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001297 MI->eraseFromParent();
1298
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001299 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001300 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001301 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001302 return true;
1303}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001304
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001305/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1306/// LR / restores LR to pc.
1307bool ARMConstantIslands::UndoLRSpillRestore() {
1308 bool MadeChange = false;
1309 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1310 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001311 if (MI->getOpcode() == ARM::tPOP_RET &&
1312 MI->getOperand(0).getReg() == ARM::PC &&
1313 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001314 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001315 MI->eraseFromParent();
1316 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001317 }
1318 }
1319 return MadeChange;
1320}