blob: 36eeffce2695b43ff055938fa4203e7e42fdb5c3 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Chengf6e7e692009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "ARMMachineFunctionInfo.h"
20#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng1b2b3e22009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattnerd71b0b02009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
34using namespace llvm;
35
Evan Chenga441c1a2009-08-14 00:32:16 +000036STATISTIC(NumCPEs, "Number of constpool entries");
37STATISTIC(NumSplit, "Number of uncond branches inserted");
38STATISTIC(NumCBrFixed, "Number of cond branches fixed");
39STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
40STATISTIC(NumTBs, "Number of table branches generated");
41STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chengf7b61a12009-08-14 18:31:44 +000042STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043
44namespace {
45 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
46 /// requires constant pool entries to be scattered among the instructions
47 /// inside a function. To do this, it completely ignores the normal LLVM
48 /// constant pool; instead, it places constants wherever it feels like with
49 /// special instructions.
50 ///
51 /// The terminology used in this pass includes:
52 /// Islands - Clumps of constants placed in the function.
53 /// Water - Potential places where an island could be formed.
54 /// CPE - A constant pool entry that has been placed somewhere, which
55 /// tracks a list of users.
56 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
58 /// by MBB Number. The two-byte pads required for Thumb alignment are
59 /// counted as part of the following block (i.e., the offset and size for
60 /// a padded block will both be ==2 mod 4).
61 std::vector<unsigned> BBSizes;
Bob Wilsonec92b492009-05-12 17:09:30 +000062
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
64 /// The two-byte pads required for Thumb alignment are counted as part of
65 /// the following block.
66 std::vector<unsigned> BBOffsets;
67
68 /// WaterList - A sorted list of basic blocks where islands could be placed
69 /// (i.e. blocks that don't fall through to the following block, due
70 /// to a return, unreachable, or unconditional branch).
71 std::vector<MachineBasicBlock*> WaterList;
72
Bob Wilsonb15413c2009-10-12 18:52:13 +000073 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
74
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 /// CPUser - One user of a constant pool, keeping the machine instruction
76 /// pointer, the constant pool being referenced, and the max displacement
77 /// allowed from the instruction to the CP.
78 struct CPUser {
79 MachineInstr *MI;
80 MachineInstr *CPEMI;
81 unsigned MaxDisp;
Evan Chengbf2498c2009-07-21 23:56:01 +000082 bool NegOk;
Evan Chengf6e7e692009-07-23 18:27:47 +000083 bool IsSoImm;
84 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
85 bool neg, bool soimm)
86 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 };
Bob Wilsonec92b492009-05-12 17:09:30 +000088
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 /// CPUsers - Keep track of all of the machine instructions that use various
90 /// constant pools and their max displacement.
91 std::vector<CPUser> CPUsers;
Bob Wilsonec92b492009-05-12 17:09:30 +000092
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 /// CPEntry - One per constant pool entry, keeping the machine instruction
94 /// pointer, the constpool index, and the number of CPUser's which
95 /// reference this entry.
96 struct CPEntry {
97 MachineInstr *CPEMI;
98 unsigned CPI;
99 unsigned RefCount;
100 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
101 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
102 };
103
104 /// CPEntries - Keep track of all of the constant pool entry machine
105 /// instructions. For each original constpool index (i.e. those that
106 /// existed upon entry to this pass), it keeps a vector of entries.
107 /// Original elements are cloned as we go along; the clones are
108 /// put in the vector of the original element, but have distinct CPIs.
109 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilsonec92b492009-05-12 17:09:30 +0000110
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 /// ImmBranch - One per immediate branch, keeping the machine instruction
112 /// pointer, conditional or unconditional, the max displacement,
113 /// and (if isCond is true) the corresponding unconditional branch
114 /// opcode.
115 struct ImmBranch {
116 MachineInstr *MI;
117 unsigned MaxDisp : 31;
118 bool isCond : 1;
119 int UncondBr;
120 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
121 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
122 };
123
124 /// ImmBranches - Keep track of all the immediate branch instructions.
125 ///
126 std::vector<ImmBranch> ImmBranches;
127
128 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
129 ///
130 SmallVector<MachineInstr*, 4> PushPopMIs;
131
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000132 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
133 SmallVector<MachineInstr*, 4> T2JumpTables;
134
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 /// HasFarJump - True if any far jump instruction has been emitted during
136 /// the branch fix up pass.
137 bool HasFarJump;
138
139 const TargetInstrInfo *TII;
Evan Cheng04f40fa2009-08-01 06:13:52 +0000140 const ARMSubtarget *STI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 ARMFunctionInfo *AFI;
142 bool isThumb;
Evan Chengf6e7e692009-07-23 18:27:47 +0000143 bool isThumb1;
David Goodwinf6154702009-06-30 18:04:13 +0000144 bool isThumb2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 public:
146 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000147 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000149 virtual bool runOnMachineFunction(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
151 virtual const char *getPassName() const {
152 return "ARM constant island placement and branch shortening pass";
153 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000154
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 private:
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000156 void DoInitialPlacement(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 std::vector<MachineInstr*> &CPEMIs);
158 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000159 void InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 const std::vector<MachineInstr*> &CPEMIs);
161 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
162 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
163 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
164 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
165 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonec92b492009-05-12 17:09:30 +0000166 bool LookForWater(CPUser&U, unsigned UserOffset,
Bob Wilson688468a2009-10-12 19:01:12 +0000167 MachineBasicBlock *&NewMBB);
Bob Wilson8454df92009-10-12 20:37:23 +0000168 MachineBasicBlock *AcceptWater(water_iterator IP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
170 MachineBasicBlock** NewMBB);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000171 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 void RemoveDeadCPEMI(MachineInstr *CPEMI);
173 bool RemoveUnusedCPEntries();
Bob Wilsonec92b492009-05-12 17:09:30 +0000174 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000175 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
176 bool DoDump = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
178 CPUser &U);
179 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000180 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000182 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
183 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
184 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 bool UndoLRSpillRestore();
Evan Chenga441c1a2009-08-14 00:32:16 +0000186 bool OptimizeThumb2Instructions(MachineFunction &MF);
187 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000188 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189
190 unsigned GetOffsetOf(MachineInstr *MI) const;
191 void dumpBBs();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000192 void verify(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 };
194 char ARMConstantIslands::ID = 0;
195}
196
197/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000198void ARMConstantIslands::verify(MachineFunction &MF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 assert(BBOffsets.size() == BBSizes.size());
200 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
201 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengf6e7e692009-07-23 18:27:47 +0000202 if (!isThumb)
203 return;
204#ifndef NDEBUG
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000205 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengf6e7e692009-07-23 18:27:47 +0000206 MBBI != E; ++MBBI) {
207 MachineBasicBlock *MBB = MBBI;
208 if (!MBB->empty() &&
209 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
210 unsigned MBBId = MBB->getNumber();
211 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
212 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 }
214 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000215#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216}
217
218/// print block size and offset information - debugging
219void ARMConstantIslands::dumpBBs() {
220 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner2c6014b2009-08-23 06:49:22 +0000221 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
222 << " size " << BBSizes[J] << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 }
224}
225
226/// createARMConstantIslandPass - returns an instance of the constpool
227/// island pass.
228FunctionPass *llvm::createARMConstantIslandPass() {
229 return new ARMConstantIslands();
230}
231
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000232bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
233 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilsonec92b492009-05-12 17:09:30 +0000234
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000235 TII = MF.getTarget().getInstrInfo();
236 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng04f40fa2009-08-01 06:13:52 +0000237 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
238
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 isThumb = AFI->isThumbFunction();
Evan Chengf6e7e692009-07-23 18:27:47 +0000240 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwinf6154702009-06-30 18:04:13 +0000241 isThumb2 = AFI->isThumb2Function();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 HasFarJump = false;
244
245 // Renumber all of the machine basic blocks in the function, guaranteeing that
246 // the numbers agree with the position of the block in the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000247 MF.RenumberBlocks();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248
Evan Chengb6a03382009-07-31 18:28:05 +0000249 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengf6e7e692009-07-23 18:27:47 +0000250 // This is so we can keep exact track of where the alignment padding goes.
251
Evan Chengb6a03382009-07-31 18:28:05 +0000252 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengf6e7e692009-07-23 18:27:47 +0000253 // aligned.
254 AFI->setAlign(isThumb1 ? 1U : 2U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255
256 // Perform the initial placement of the constant pool entries. To start with,
257 // we put them all at the end of the function.
258 std::vector<MachineInstr*> CPEMIs;
259 if (!MCP.isEmpty()) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000260 DoInitialPlacement(MF, CPEMIs);
Evan Chengf6e7e692009-07-23 18:27:47 +0000261 if (isThumb1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 AFI->setAlign(2U);
263 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000264
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 /// The next UID to take is the first unused one.
Evan Chengd3c573a2008-11-08 00:51:41 +0000266 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilsonec92b492009-05-12 17:09:30 +0000267
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 // Do the initial scan of the function, building up information about the
269 // sizes of each block, the location of all the water, and finding all of the
270 // constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000271 InitialFunctionScan(MF, CPEMIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 CPEMIs.clear();
Bob Wilsonec92b492009-05-12 17:09:30 +0000273
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 /// Remove dead constant pool entries.
275 RemoveUnusedCPEntries();
276
277 // Iteratively place constant pool entries and fix up branches until there
278 // is no change.
279 bool MadeChange = false;
Evan Cheng3c05d132009-08-07 07:35:21 +0000280 unsigned NoCPIters = 0, NoBRIters = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 while (true) {
Evan Cheng3c05d132009-08-07 07:35:21 +0000282 bool CPChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000284 CPChange |= HandleConstantPoolUser(MF, i);
285 if (CPChange && ++NoCPIters > 30)
286 llvm_unreachable("Constant Island pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000288
289 bool BRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000291 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
292 if (BRChange && ++NoBRIters > 30)
293 llvm_unreachable("Branch Fix Up pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000295
296 if (!CPChange && !BRChange)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 break;
298 MadeChange = true;
299 }
300
Evan Chenga441c1a2009-08-14 00:32:16 +0000301 // Shrink 32-bit Thumb2 branch, load, and store instructions.
302 if (isThumb2)
303 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng04f40fa2009-08-01 06:13:52 +0000304
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000306 verify(MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307
308 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
309 // Undo the spill / restore of LR if possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000310 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311 MadeChange |= UndoLRSpillRestore();
312
313 BBSizes.clear();
314 BBOffsets.clear();
315 WaterList.clear();
316 CPUsers.clear();
317 CPEntries.clear();
318 ImmBranches.clear();
319 PushPopMIs.clear();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000320 T2JumpTables.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
322 return MadeChange;
323}
324
325/// DoInitialPlacement - Perform the initial placement of the constant pool
326/// entries. To start with, we put them all at the end of the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000327void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +0000328 std::vector<MachineInstr*> &CPEMIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 // Create the basic block to hold the CPE's.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000330 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
331 MF.push_back(BB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000332
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 // Add all of the constants from the constant pool to the end block, use an
334 // identity mapping of CPI's to CPE's.
335 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000336 MF.getConstantPool()->getConstants();
Bob Wilsonec92b492009-05-12 17:09:30 +0000337
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000338 const TargetData &TD = *MF.getTarget().getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000340 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
342 // we would have to pad them out or something so that instructions stay
343 // aligned.
344 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
345 MachineInstr *CPEMI =
Dale Johannesene8a10c42009-02-13 02:25:56 +0000346 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 .addImm(i).addConstantPoolIndex(i).addImm(Size);
348 CPEMIs.push_back(CPEMI);
349
350 // Add a new CPEntry, but no corresponding CPUser yet.
351 std::vector<CPEntry> CPEs;
352 CPEs.push_back(CPEntry(CPEMI, i));
353 CPEntries.push_back(CPEs);
354 NumCPEs++;
Chris Lattner2c6014b2009-08-23 06:49:22 +0000355 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
356 << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 }
358}
359
360/// BBHasFallthrough - Return true if the specified basic block can fallthrough
361/// into the block immediately after it.
362static bool BBHasFallthrough(MachineBasicBlock *MBB) {
363 // Get the next machine basic block in the function.
364 MachineFunction::iterator MBBI = MBB;
365 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
366 return false;
Bob Wilsonec92b492009-05-12 17:09:30 +0000367
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 MachineBasicBlock *NextBB = next(MBBI);
369 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
370 E = MBB->succ_end(); I != E; ++I)
371 if (*I == NextBB)
372 return true;
Bob Wilsonec92b492009-05-12 17:09:30 +0000373
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 return false;
375}
376
377/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
378/// look up the corresponding CPEntry.
379ARMConstantIslands::CPEntry
380*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
381 const MachineInstr *CPEMI) {
382 std::vector<CPEntry> &CPEs = CPEntries[CPI];
383 // Number of entries per constpool index should be small, just do a
384 // linear search.
385 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
386 if (CPEs[i].CPEMI == CPEMI)
387 return &CPEs[i];
388 }
389 return NULL;
390}
391
392/// InitialFunctionScan - Do the initial scan of the function, building up
393/// information about the sizes of each block, the location of all the water,
394/// and finding all of the constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000395void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 const std::vector<MachineInstr*> &CPEMIs) {
397 unsigned Offset = 0;
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000398 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 MBBI != E; ++MBBI) {
400 MachineBasicBlock &MBB = *MBBI;
Bob Wilsonec92b492009-05-12 17:09:30 +0000401
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 // If this block doesn't fall through into the next MBB, then this is
403 // 'water' that a constant pool island could be placed.
404 if (!BBHasFallthrough(&MBB))
405 WaterList.push_back(&MBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000406
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407 unsigned MBBSize = 0;
408 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
409 I != E; ++I) {
410 // Add instruction size to MBBSize.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000411 MBBSize += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
413 int Opc = I->getOpcode();
Chris Lattner5b930372008-01-07 07:27:27 +0000414 if (I->getDesc().isBranch()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 bool isCond = false;
416 unsigned Bits = 0;
417 unsigned Scale = 1;
418 int UOpc = Opc;
419 switch (Opc) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000420 default:
421 continue; // Ignore other JT branches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 case ARM::tBR_JTr:
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000423 // A Thumb1 table jump may involve padding; for the offsets to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 // be right, functions containing these must be 4-byte aligned.
425 AFI->setAlign(2U);
426 if ((Offset+MBBSize)%4 != 0)
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000427 // FIXME: Add a pseudo ALIGN instruction instead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 MBBSize += 2; // padding
429 continue; // Does not get an entry in ImmBranches
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000430 case ARM::t2BR_JT:
431 T2JumpTables.push_back(I);
432 continue; // Does not get an entry in ImmBranches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 case ARM::Bcc:
434 isCond = true;
435 UOpc = ARM::B;
436 // Fallthrough
437 case ARM::B:
438 Bits = 24;
439 Scale = 4;
440 break;
441 case ARM::tBcc:
442 isCond = true;
443 UOpc = ARM::tB;
444 Bits = 8;
445 Scale = 2;
446 break;
447 case ARM::tB:
448 Bits = 11;
449 Scale = 2;
450 break;
David Goodwinf6154702009-06-30 18:04:13 +0000451 case ARM::t2Bcc:
452 isCond = true;
453 UOpc = ARM::t2B;
454 Bits = 20;
455 Scale = 2;
456 break;
457 case ARM::t2B:
458 Bits = 24;
459 Scale = 2;
460 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 }
462
463 // Record this immediate branch.
464 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
465 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
466 }
467
468 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
469 PushPopMIs.push_back(I);
470
Evan Chengf6e7e692009-07-23 18:27:47 +0000471 if (Opc == ARM::CONSTPOOL_ENTRY)
472 continue;
473
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 // Scan the instructions for constant pool operands.
475 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000476 if (I->getOperand(op).isCPI()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 // We found one. The addressing mode tells us the max displacement
478 // from the PC that this instruction permits.
Bob Wilsonec92b492009-05-12 17:09:30 +0000479
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 // Basic size info comes from the TSFlags field.
481 unsigned Bits = 0;
482 unsigned Scale = 1;
Evan Chengbf2498c2009-07-21 23:56:01 +0000483 bool NegOk = false;
Evan Chengf6e7e692009-07-23 18:27:47 +0000484 bool IsSoImm = false;
485
486 switch (Opc) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000487 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000488 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengf6e7e692009-07-23 18:27:47 +0000489 break;
490
491 // Taking the address of a CP entry.
492 case ARM::LEApcrel:
493 // This takes a SoImm, which is 8 bit immediate rotated. We'll
494 // pretend the maximum offset is 255 * 4. Since each instruction
495 // 4 byte wide, this is always correct. We'llc heck for other
496 // displacements that fits in a SoImm as well.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 Bits = 8;
Evan Chengf6e7e692009-07-23 18:27:47 +0000498 Scale = 4;
499 NegOk = true;
500 IsSoImm = true;
501 break;
502 case ARM::t2LEApcrel:
503 Bits = 12;
Evan Chengbf2498c2009-07-21 23:56:01 +0000504 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000506 case ARM::tLEApcrel:
507 Bits = 8;
508 Scale = 4;
509 break;
510
511 case ARM::LDR:
512 case ARM::LDRcp:
513 case ARM::t2LDRpci:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 Bits = 12; // +-offset_12
Evan Chengbf2498c2009-07-21 23:56:01 +0000515 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000517
518 case ARM::tLDRpci:
519 case ARM::tLDRcp:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 Bits = 8;
521 Scale = 4; // +(offset_8*4)
522 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000523
524 case ARM::FLDD:
525 case ARM::FLDS:
526 Bits = 8;
527 Scale = 4; // +-(offset_8*4)
528 NegOk = true;
Evan Cheng532cdc52009-06-29 07:51:04 +0000529 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 }
531
532 // Remember that this is a user of a CP entry.
Chris Lattner6017d482007-12-30 23:10:15 +0000533 unsigned CPI = I->getOperand(op).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chengf7b61a12009-08-14 18:31:44 +0000535 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengf6e7e692009-07-23 18:27:47 +0000536 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537
538 // Increment corresponding CPEntry reference count.
539 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
540 assert(CPE && "Cannot find a corresponding CPEntry!");
541 CPE->RefCount++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000542
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 // Instructions can only use one CP entry, don't bother scanning the
544 // rest of the operands.
545 break;
546 }
547 }
548
549 // In thumb mode, if this block is a constpool island, we may need padding
550 // so it's aligned on 4 byte boundary.
551 if (isThumb &&
552 !MBB.empty() &&
553 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
554 (Offset%4) != 0)
555 MBBSize += 2;
556
557 BBSizes.push_back(MBBSize);
558 BBOffsets.push_back(Offset);
559 Offset += MBBSize;
560 }
561}
562
563/// GetOffsetOf - Return the current offset of the specified machine instruction
564/// from the start of the function. This offset changes as stuff is moved
565/// around inside the function.
566unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
567 MachineBasicBlock *MBB = MI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000568
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 // The offset is composed of two things: the sum of the sizes of all MBB's
570 // before this instruction's block, and the offset from the start of the block
571 // it is in.
572 unsigned Offset = BBOffsets[MBB->getNumber()];
573
574 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
575 // alignment padding, and compensate if so.
Bob Wilsonec92b492009-05-12 17:09:30 +0000576 if (isThumb &&
577 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 Offset%4 != 0)
579 Offset += 2;
580
581 // Sum instructions before MI in MBB.
582 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
583 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
584 if (&*I == MI) return Offset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000585 Offset += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
587}
588
589/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
590/// ID.
591static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
592 const MachineBasicBlock *RHS) {
593 return LHS->getNumber() < RHS->getNumber();
594}
595
596/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
597/// machine function, it upsets all of the block numbers. Renumber the blocks
598/// and update the arrays that parallel this numbering.
599void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
600 // Renumber the MBB's to keep them consequtive.
601 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000602
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 // Insert a size into BBSizes to align it properly with the (newly
604 // renumbered) block numbers.
605 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
606
607 // Likewise for BBOffsets.
608 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000609
610 // Next, update WaterList. Specifically, we need to add NewMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 // available water after it.
Bob Wilsonb15413c2009-10-12 18:52:13 +0000612 water_iterator IP =
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
614 CompareMBBNumbers);
615 WaterList.insert(IP, NewBB);
616}
617
618
619/// Split the basic block containing MI into two blocks, which are joined by
620/// an unconditional branch. Update datastructures and renumber blocks to
621/// account for this change and returns the newly created block.
622MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
623 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman221a4372008-07-07 23:14:23 +0000624 MachineFunction &MF = *OrigBB->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625
626 // Create a new MBB for the code after the OrigBB.
Bob Wilsonec92b492009-05-12 17:09:30 +0000627 MachineBasicBlock *NewBB =
628 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman221a4372008-07-07 23:14:23 +0000630 MF.insert(MBBI, NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 // Splice the instructions starting with MI over to NewBB.
633 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilsonec92b492009-05-12 17:09:30 +0000634
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 // Add an unconditional branch from OrigBB to NewBB.
636 // Note the new unconditional branch is not being recorded.
Dale Johannesene8a10c42009-02-13 02:25:56 +0000637 // There doesn't seem to be meaningful DebugInfo available; this doesn't
638 // correspond to anything in the source.
Evan Cheng451192e2009-07-07 01:16:41 +0000639 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
640 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 NumSplit++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000642
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 // Update the CFG. All succs of OrigBB are now succs of NewBB.
644 while (!OrigBB->succ_empty()) {
645 MachineBasicBlock *Succ = *OrigBB->succ_begin();
646 OrigBB->removeSuccessor(Succ);
647 NewBB->addSuccessor(Succ);
Bob Wilsonec92b492009-05-12 17:09:30 +0000648
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 // This pass should be run after register allocation, so there should be no
650 // PHI nodes to update.
651 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
652 && "PHI nodes should be eliminated by now!");
653 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000654
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 // OrigBB branches to NewBB.
656 OrigBB->addSuccessor(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 // Update internal data structures to account for the newly inserted MBB.
659 // This is almost the same as UpdateForInsertedWaterBlock, except that
660 // the Water goes after OrigBB, not NewBB.
Dan Gohman221a4372008-07-07 23:14:23 +0000661 MF.RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000662
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 // Insert a size into BBSizes to align it properly with the (newly
664 // renumbered) block numbers.
665 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000666
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 // Likewise for BBOffsets.
668 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
669
Bob Wilsonec92b492009-05-12 17:09:30 +0000670 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 // available water after it (but not if it's already there, which happens
672 // when splitting before a conditional branch that is followed by an
673 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonb15413c2009-10-12 18:52:13 +0000674 water_iterator IP =
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
676 CompareMBBNumbers);
677 MachineBasicBlock* WaterBB = *IP;
678 if (WaterBB == OrigBB)
679 WaterList.insert(next(IP), NewBB);
680 else
681 WaterList.insert(IP, OrigBB);
682
683 // Figure out how large the first NewMBB is. (It cannot
684 // contain a constpool_entry or tablejump.)
685 unsigned NewBBSize = 0;
686 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
687 I != E; ++I)
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000688 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilsonec92b492009-05-12 17:09:30 +0000689
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 unsigned OrigBBI = OrigBB->getNumber();
691 unsigned NewBBI = NewBB->getNumber();
692 // Set the size of NewBB in BBSizes.
693 BBSizes[NewBBI] = NewBBSize;
Bob Wilsonec92b492009-05-12 17:09:30 +0000694
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 // We removed instructions from UserMBB, subtract that off from its size.
696 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng04f40fa2009-08-01 06:13:52 +0000697 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 BBSizes[OrigBBI] -= NewBBSize - delta;
699
700 // ...and adjust BBOffsets for NewBB accordingly.
701 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
702
703 // All BBOffsets following these blocks must be modified.
704 AdjustBBOffsetsAfter(NewBB, delta);
705
706 return NewBB;
707}
708
709/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilsonec92b492009-05-12 17:09:30 +0000710/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711/// constant pool entry).
Bob Wilsonec92b492009-05-12 17:09:30 +0000712bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000713 unsigned TrialOffset, unsigned MaxDisp,
714 bool NegativeOK, bool IsSoImm) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000715 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
716 // purposes of the displacement computation; compensate for that here.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 // Effectively, the valid range of displacements is 2 bytes smaller for such
718 // references.
Evan Chengf7b61a12009-08-14 18:31:44 +0000719 unsigned TotalAdj = 0;
720 if (isThumb && UserOffset%4 !=0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 UserOffset -= 2;
Evan Chengf7b61a12009-08-14 18:31:44 +0000722 TotalAdj = 2;
723 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 // CPEs will be rounded up to a multiple of 4.
Evan Chengf7b61a12009-08-14 18:31:44 +0000725 if (isThumb && TrialOffset%4 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 TrialOffset += 2;
Evan Chengf7b61a12009-08-14 18:31:44 +0000727 TotalAdj += 2;
728 }
729
730 // In Thumb2 mode, later branch adjustments can shift instructions up and
731 // cause alignment change. In the worst case scenario this can cause the
732 // user's effective address to be subtracted by 2 and the CPE's address to
733 // be plus 2.
734 if (isThumb2 && TotalAdj != 4)
735 MaxDisp -= (4 - TotalAdj);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736
737 if (UserOffset <= TrialOffset) {
738 // User before the Trial.
Evan Chengf6e7e692009-07-23 18:27:47 +0000739 if (TrialOffset - UserOffset <= MaxDisp)
740 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000741 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 } else if (NegativeOK) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000743 if (UserOffset - TrialOffset <= MaxDisp)
744 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000745 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 }
747 return false;
748}
749
750/// WaterIsInRange - Returns true if a CPE placed after the specified
751/// Water (a basic block) will be in range for the specific MI.
752
753bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000754 MachineBasicBlock* Water, CPUser &U) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 unsigned MaxDisp = U.MaxDisp;
Bob Wilsonec92b492009-05-12 17:09:30 +0000756 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757 BBSizes[Water->getNumber()];
758
759 // If the CPE is to be inserted before the instruction, that will raise
760 // the offset of the instruction. (Currently applies only to ARM, so
761 // no alignment compensation attempted here.)
762 if (CPEOffset < UserOffset)
763 UserOffset += U.CPEMI->getOperand(2).getImm();
764
Evan Chengf6e7e692009-07-23 18:27:47 +0000765 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766}
767
768/// CPEIsInRange - Returns true if the distance between specific MI and
769/// specific ConstPool entry instruction can fit in MI's displacement field.
770bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000771 MachineInstr *CPEMI, unsigned MaxDisp,
772 bool NegOk, bool DoDump) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 unsigned CPEOffset = GetOffsetOf(CPEMI);
774 assert(CPEOffset%4 == 0 && "Misaligned CPE");
775
776 if (DoDump) {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000777 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
778 << " max delta=" << MaxDisp
779 << " insn address=" << UserOffset
780 << " CPE address=" << CPEOffset
781 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 }
783
Evan Chengbf2498c2009-07-21 23:56:01 +0000784 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785}
786
Evan Cheng10361732009-01-28 00:53:34 +0000787#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
789/// unconditionally branches to its only successor.
790static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
791 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
792 return false;
793
794 MachineBasicBlock *Succ = *MBB->succ_begin();
795 MachineBasicBlock *Pred = *MBB->pred_begin();
796 MachineInstr *PredMI = &Pred->back();
David Goodwinf6154702009-06-30 18:04:13 +0000797 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
798 || PredMI->getOpcode() == ARM::t2B)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 return PredMI->getOperand(0).getMBB() == Succ;
800 return false;
801}
Evan Cheng10361732009-01-28 00:53:34 +0000802#endif // NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803
Bob Wilsonec92b492009-05-12 17:09:30 +0000804void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 int delta) {
806 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengf6e7e692009-07-23 18:27:47 +0000807 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
808 i < e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 BBOffsets[i] += delta;
810 // If some existing blocks have padding, adjust the padding as needed, a
811 // bit tricky. delta can be negative so don't use % on that.
Evan Chengf6e7e692009-07-23 18:27:47 +0000812 if (!isThumb)
813 continue;
814 MachineBasicBlock *MBB = MBBI;
815 if (!MBB->empty()) {
816 // Constant pool entries require padding.
817 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng275468a2009-08-11 07:36:14 +0000818 unsigned OldOffset = BBOffsets[i] - delta;
819 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000820 // add new padding
821 BBSizes[i] += 2;
822 delta += 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000823 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000824 // remove existing padding
Evan Cheng275468a2009-08-11 07:36:14 +0000825 BBSizes[i] -= 2;
Evan Chengf6e7e692009-07-23 18:27:47 +0000826 delta -= 2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000829 // Thumb1 jump tables require padding. They should be at the end;
830 // following unconditional branches are removed by AnalyzeBranch.
Evan Chenga609c1d2009-07-24 18:20:44 +0000831 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000832 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng275468a2009-08-11 07:36:14 +0000833 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
834 unsigned OldMIOffset = NewMIOffset - delta;
835 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000836 // remove existing padding
837 BBSizes[i] -= 2;
838 delta -= 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000839 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000840 // add new padding
841 BBSizes[i] += 2;
842 delta += 2;
843 }
844 }
845 if (delta==0)
846 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000848 MBBI = next(MBBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850}
851
852/// DecrementOldEntry - find the constant pool entry with index CPI
853/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilsonec92b492009-05-12 17:09:30 +0000854/// becomes 0 remove the entry and instruction. Returns true if we removed
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855/// the entry, false if we didn't.
856
857bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
858 // Find the old entry. Eliminate it if it is no longer used.
859 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
860 assert(CPE && "Unexpected!");
861 if (--CPE->RefCount == 0) {
862 RemoveDeadCPEMI(CPEMI);
863 CPE->CPEMI = NULL;
864 NumCPEs--;
865 return true;
866 }
867 return false;
868}
869
870/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
871/// if not, see if an in-range clone of the CPE is in range, and if so,
872/// change the data structures so the user references the clone. Returns:
873/// 0 = no existing entry found
874/// 1 = entry found, and there were no code insertions or deletions
875/// 2 = entry found, and there were code insertions or deletions
876int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
877{
878 MachineInstr *UserMI = U.MI;
879 MachineInstr *CPEMI = U.CPEMI;
880
881 // Check to see if the CPE is already in-range.
Evan Chengbf2498c2009-07-21 23:56:01 +0000882 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner2c6014b2009-08-23 06:49:22 +0000883 DEBUG(errs() << "In range\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 return 1;
885 }
886
887 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner6017d482007-12-30 23:10:15 +0000888 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 std::vector<CPEntry> &CPEs = CPEntries[CPI];
890 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
891 // We already tried this one
892 if (CPEs[i].CPEMI == CPEMI)
893 continue;
894 // Removing CPEs can leave empty entries, skip
895 if (CPEs[i].CPEMI == NULL)
896 continue;
Evan Chengbf2498c2009-07-21 23:56:01 +0000897 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner2c6014b2009-08-23 06:49:22 +0000898 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
899 << CPEs[i].CPI << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 // Point the CPUser node to the replacement
901 U.CPEMI = CPEs[i].CPEMI;
902 // Change the CPI in the instruction operand to refer to the clone.
903 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000904 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +0000905 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 break;
907 }
908 // Adjust the refcount of the clone...
909 CPEs[i].RefCount++;
910 // ...and the original. If we didn't remove the old entry, none of the
911 // addresses changed, so we don't need another pass.
912 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
913 }
914 }
915 return 0;
916}
917
918/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
919/// the specific unconditional branch instruction.
920static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwinf6154702009-06-30 18:04:13 +0000921 switch (Opc) {
922 case ARM::tB:
923 return ((1<<10)-1)*2;
924 case ARM::t2B:
925 return ((1<<23)-1)*2;
926 default:
927 break;
928 }
Jim Grosbach770d7182009-08-11 15:33:49 +0000929
David Goodwinf6154702009-06-30 18:04:13 +0000930 return ((1<<23)-1)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931}
932
933/// AcceptWater - Small amount of common code factored out of the following.
Bob Wilson8454df92009-10-12 20:37:23 +0000934///
935MachineBasicBlock *ARMConstantIslands::AcceptWater(water_iterator IP) {
Chris Lattner2c6014b2009-08-23 06:49:22 +0000936 DEBUG(errs() << "found water in range\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 // Remove the original WaterList entry; we want subsequent
938 // insertions in this vicinity to go after the one we're
939 // about to insert. This considerably reduces the number
940 // of times we have to move the same CPE more than once.
941 WaterList.erase(IP);
942 // CPE goes before following block (NewMBB).
Bob Wilson8454df92009-10-12 20:37:23 +0000943 return next(MachineFunction::iterator(*IP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944}
945
946/// LookForWater - look for an existing entry in the WaterList in which
947/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson688468a2009-10-12 19:01:12 +0000948/// Returns true if found, false if not. If it returns true, NewMBB
Bob Wilsone5001732009-10-12 21:23:15 +0000949/// is set to the WaterList entry. For Thumb, prefer water that will not
950/// introduce padding to water that will. To ensure that this pass
951/// terminates, the CPE location for a particular CPUser is only allowed to
952/// move to a lower address, so search backward from the end of the list and
953/// prefer the first water that is in range.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilson688468a2009-10-12 19:01:12 +0000955 MachineBasicBlock *&NewMBB) {
Bob Wilson93312092009-10-12 19:04:03 +0000956 if (WaterList.empty())
957 return false;
958
Bob Wilson31d9eb52009-10-12 20:45:53 +0000959 bool FoundWaterThatWouldPad = false;
960 water_iterator IPThatWouldPad;
Bob Wilson93312092009-10-12 19:04:03 +0000961 for (water_iterator IP = prior(WaterList.end()),
962 B = WaterList.begin();; --IP) {
963 MachineBasicBlock* WaterBB = *IP;
Bob Wilsone5001732009-10-12 21:23:15 +0000964 // Check if water is in range and at a lower address than the current one.
965 if (WaterIsInRange(UserOffset, WaterBB, U) &&
966 WaterBB->getNumber() < U.CPEMI->getParent()->getNumber()) {
Bob Wilson93312092009-10-12 19:04:03 +0000967 unsigned WBBId = WaterBB->getNumber();
968 if (isThumb &&
969 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
970 // This is valid Water, but would introduce padding. Remember
971 // it in case we don't find any Water that doesn't do this.
Bob Wilson31d9eb52009-10-12 20:45:53 +0000972 if (!FoundWaterThatWouldPad) {
973 FoundWaterThatWouldPad = true;
Bob Wilson93312092009-10-12 19:04:03 +0000974 IPThatWouldPad = IP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 }
Bob Wilson93312092009-10-12 19:04:03 +0000976 } else {
Bob Wilson8454df92009-10-12 20:37:23 +0000977 NewMBB = AcceptWater(IP);
Bob Wilson93312092009-10-12 19:04:03 +0000978 return true;
Evan Chengf6e7e692009-07-23 18:27:47 +0000979 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 }
Bob Wilson93312092009-10-12 19:04:03 +0000981 if (IP == B)
982 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 }
Bob Wilson31d9eb52009-10-12 20:45:53 +0000984 if (FoundWaterThatWouldPad) {
Bob Wilson8454df92009-10-12 20:37:23 +0000985 NewMBB = AcceptWater(IPThatWouldPad);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 return true;
987 }
988 return false;
989}
990
Bob Wilsonec92b492009-05-12 17:09:30 +0000991/// CreateNewWater - No existing WaterList entry will work for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
993/// block is used if in range, and the conditional branch munged so control
994/// flow is correct. Otherwise the block is split to create a hole with an
995/// unconditional branch around it. In either case *NewMBB is set to a
996/// block following which the new island can be inserted (the WaterList
997/// is not adjusted).
998
Bob Wilsonec92b492009-05-12 17:09:30 +0000999void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 unsigned UserOffset, MachineBasicBlock** NewMBB) {
1001 CPUser &U = CPUsers[CPUserIndex];
1002 MachineInstr *UserMI = U.MI;
1003 MachineInstr *CPEMI = U.CPEMI;
1004 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +00001005 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 BBSizes[UserMBB->getNumber()];
1007 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1008
1009 // If the use is at the end of the block, or the end of the block
1010 // is within range, make new water there. (The addition below is
Evan Chengf6e7e692009-07-23 18:27:47 +00001011 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
1012 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 // inside OffsetIsInRange.
Bob Wilsonec92b492009-05-12 17:09:30 +00001014 // If the block ends in an unconditional branch already, it is water,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 // and is known to be out of range, so we'll always be adding a branch.)
1016 if (&UserMBB->back() == UserMI ||
Evan Chengf6e7e692009-07-23 18:27:47 +00001017 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1018 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner2c6014b2009-08-23 06:49:22 +00001019 DEBUG(errs() << "Split at end of block\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if (&UserMBB->back() == UserMI)
1021 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1022 *NewMBB = next(MachineFunction::iterator(UserMBB));
1023 // Add an unconditional branch from UserMBB to fallthrough block.
1024 // Record it for branch lengthening; this new branch will not get out of
1025 // range, but if the preceding conditional branch is out of range, the
1026 // targets will be exchanged, and the altered branch may be out of
1027 // range, so the machinery has to know about it.
David Goodwinf6154702009-06-30 18:04:13 +00001028 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesene8a10c42009-02-13 02:25:56 +00001029 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1030 TII->get(UncondBr)).addMBB(*NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilsonec92b492009-05-12 17:09:30 +00001032 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 MaxDisp, false, UncondBr));
Evan Chengf6e7e692009-07-23 18:27:47 +00001034 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 BBSizes[UserMBB->getNumber()] += delta;
1036 AdjustBBOffsetsAfter(UserMBB, delta);
1037 } else {
1038 // What a big block. Find a place within the block to split it.
Evan Chengf6e7e692009-07-23 18:27:47 +00001039 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 // and constant pool entries are 4 bytes: if instruction I references
1041 // island CPE, and instruction I+1 references CPE', it will
1042 // not work well to put CPE as far forward as possible, since then
1043 // CPE' cannot immediately follow it (that location is 2 bytes
1044 // farther away from I+1 than CPE was from I) and we'd need to create
1045 // a new island. So, we make a first guess, then walk through the
1046 // instructions between the one currently being looked at and the
1047 // possible insertion point, and make sure any other instructions
1048 // that reference CPEs will be able to use the same island area;
1049 // if not, we back up the insertion point.
1050
1051 // The 4 in the following is for the unconditional branch we'll be
Evan Chengf6e7e692009-07-23 18:27:47 +00001052 // inserting (allows for long branch on Thumb1). Alignment of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 // island is handled inside OffsetIsInRange.
1054 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1055 // This could point off the end of the block if we've already got
1056 // constant pool entries following this block; only the last one is
1057 // in the water list. Back past any possible branches (allow for a
1058 // conditional and a maximally long unconditional).
1059 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilsonec92b492009-05-12 17:09:30 +00001060 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengf6e7e692009-07-23 18:27:47 +00001061 (isThumb1 ? 6 : 8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 unsigned EndInsertOffset = BaseInsertOffset +
1063 CPEMI->getOperand(2).getImm();
1064 MachineBasicBlock::iterator MI = UserMI;
1065 ++MI;
1066 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001067 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 Offset < BaseInsertOffset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001069 Offset += TII->GetInstSizeInBytes(MI),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 MI = next(MI)) {
1071 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001072 CPUser &U = CPUsers[CPUIndex];
Bob Wilsonec92b492009-05-12 17:09:30 +00001073 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +00001074 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1075 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1076 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 }
1078 // This is overly conservative, as we don't account for CPEMIs
1079 // being reused within the block, but it doesn't matter much.
1080 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1081 CPUIndex++;
1082 }
1083 }
Chris Lattner2c6014b2009-08-23 06:49:22 +00001084 DEBUG(errs() << "Split in middle of big block\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1086 }
1087}
1088
1089/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsond6985d52009-05-12 17:35:29 +00001090/// is out-of-range. If so, pick up the constant pool value and move it some
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091/// place in-range. Return true if we changed any addresses (thus must run
1092/// another pass of branch lengthening), false otherwise.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001093bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +00001094 unsigned CPUserIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 CPUser &U = CPUsers[CPUserIndex];
1096 MachineInstr *UserMI = U.MI;
1097 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001098 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 unsigned Size = CPEMI->getOperand(2).getImm();
1100 MachineBasicBlock *NewMBB;
1101 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga441c1a2009-08-14 00:32:16 +00001102 // hardware keeps in the PC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1104
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 // See if the current entry is within range, or there is a clone of it
1106 // in range.
1107 int result = LookForExistingCPEntry(U, UserOffset);
1108 if (result==1) return false;
1109 else if (result==2) return true;
1110
1111 // No existing clone of this CPE is within range.
1112 // We will be generating a new clone. Get a UID for it.
Bob Wilsond6985d52009-05-12 17:35:29 +00001113 unsigned ID = AFI->createConstPoolEntryUId();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114
Bob Wilsone5001732009-10-12 21:23:15 +00001115 // Look for water where we can place this CPE.
Bob Wilson688468a2009-10-12 19:01:12 +00001116 if (!LookForWater(U, UserOffset, NewMBB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 // No water found.
Chris Lattner2c6014b2009-08-23 06:49:22 +00001118 DEBUG(errs() << "No water found\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1120 }
1121
1122 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001123 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1124 MF.insert(NewMBB, NewIsland);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125
1126 // Update internal data structures to account for the newly inserted MBB.
1127 UpdateForInsertedWaterBlock(NewIsland);
1128
1129 // Decrement the old entry, and remove it if refcount becomes 0.
1130 DecrementOldEntry(CPI, CPEMI);
1131
1132 // Now that we have an island to add the CPE to, clone the original CPE and
1133 // add it to the island.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001134 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1135 TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1137 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1138 NumCPEs++;
1139
1140 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1141 // Compensate for .align 2 in thumb mode.
Bob Wilsonec92b492009-05-12 17:09:30 +00001142 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 Size += 2;
1144 // Increase the size of the island block to account for the new entry.
1145 BBSizes[NewIsland->getNumber()] += Size;
1146 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilsonec92b492009-05-12 17:09:30 +00001147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 // Finally, change the CPI in the instruction operand to be ID.
1149 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001150 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +00001151 UserMI->getOperand(i).setIndex(ID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 break;
1153 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001154
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001155 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1156 << '\t' << *UserMI);
Bob Wilsonec92b492009-05-12 17:09:30 +00001157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 return true;
1159}
1160
1161/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1162/// sizes and offsets of impacted basic blocks.
1163void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1164 MachineBasicBlock *CPEBB = CPEMI->getParent();
1165 unsigned Size = CPEMI->getOperand(2).getImm();
1166 CPEMI->eraseFromParent();
1167 BBSizes[CPEBB->getNumber()] -= Size;
1168 // All succeeding offsets have the current size value added in, fix this.
1169 if (CPEBB->empty()) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001170 // In thumb1 mode, the size of island may be padded by two to compensate for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 // the alignment requirement. Then it will now be 2 when the block is
1172 // empty, so fix this.
1173 // All succeeding offsets have the current size value added in, fix this.
1174 if (BBSizes[CPEBB->getNumber()] != 0) {
1175 Size += BBSizes[CPEBB->getNumber()];
1176 BBSizes[CPEBB->getNumber()] = 0;
1177 }
1178 }
1179 AdjustBBOffsetsAfter(CPEBB, -Size);
1180 // An island has only one predecessor BB and one successor BB. Check if
1181 // this BB's predecessor jumps directly to this BB's successor. This
1182 // shouldn't happen currently.
1183 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1184 // FIXME: remove the empty blocks after all the work is done?
1185}
1186
1187/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1188/// are zero.
1189bool ARMConstantIslands::RemoveUnusedCPEntries() {
1190 unsigned MadeChange = false;
1191 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1192 std::vector<CPEntry> &CPEs = CPEntries[i];
1193 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1194 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1195 RemoveDeadCPEMI(CPEs[j].CPEMI);
1196 CPEs[j].CPEMI = NULL;
1197 MadeChange = true;
1198 }
1199 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001200 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 return MadeChange;
1202}
1203
1204/// BBIsInRange - Returns true if the distance between specific MI and
1205/// specific BB can fit in MI's displacement field.
1206bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1207 unsigned MaxDisp) {
1208 unsigned PCAdj = isThumb ? 4 : 8;
1209 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1210 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1211
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001212 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1213 << " from BB#" << MI->getParent()->getNumber()
1214 << " max delta=" << MaxDisp
1215 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1216 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217
1218 if (BrOffset <= DestOffset) {
1219 // Branch before the Dest.
1220 if (DestOffset-BrOffset <= MaxDisp)
1221 return true;
1222 } else {
1223 if (BrOffset-DestOffset <= MaxDisp)
1224 return true;
1225 }
1226 return false;
1227}
1228
1229/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1230/// away to fit in its displacement field.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001231bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001233 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234
1235 // Check to see if the DestBB is already in-range.
1236 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1237 return false;
1238
1239 if (!Br.isCond)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001240 return FixUpUnconditionalBr(MF, Br);
1241 return FixUpConditionalBr(MF, Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242}
1243
1244/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1245/// too far away to fit in its displacement field. If the LR register has been
1246/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsond6985d52009-05-12 17:35:29 +00001247/// Otherwise, add an intermediate branch instruction to a branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001249ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 MachineInstr *MI = Br.MI;
1251 MachineBasicBlock *MBB = MI->getParent();
Evan Chengd6053af2009-08-07 05:45:07 +00001252 if (!isThumb1)
1253 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254
1255 // Use BL to implement far jump.
1256 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner86bb02f2008-01-11 18:10:50 +00001257 MI->setDesc(TII->get(ARM::tBfar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 BBSizes[MBB->getNumber()] += 2;
1259 AdjustBBOffsetsAfter(MBB, 2);
1260 HasFarJump = true;
1261 NumUBrFixed++;
1262
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001263 DEBUG(errs() << " Changed B to long jump " << *MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264
1265 return true;
1266}
1267
1268/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1269/// far away to fit in its displacement field. It is converted to an inverse
1270/// conditional branch + an unconditional branch to the destination.
1271bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001272ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001274 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275
Bob Wilsond6985d52009-05-12 17:35:29 +00001276 // Add an unconditional branch to the destination and invert the branch
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 // condition to jump over it:
1278 // blt L1
1279 // =>
1280 // bge L2
1281 // b L1
1282 // L2:
Chris Lattnera96056a2007-12-30 20:49:49 +00001283 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 CC = ARMCC::getOppositeCondition(CC);
1285 unsigned CCReg = MI->getOperand(2).getReg();
1286
1287 // If the branch is at the end of its MBB and that has a fall-through block,
1288 // direct the updated conditional branch to the fall-through block. Otherwise,
1289 // split the MBB before the next instruction.
1290 MachineBasicBlock *MBB = MI->getParent();
1291 MachineInstr *BMI = &MBB->back();
1292 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1293
1294 NumCBrFixed++;
1295 if (BMI != MI) {
Dan Gohman221a4372008-07-07 23:14:23 +00001296 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsond6985d52009-05-12 17:35:29 +00001298 // Last MI in the BB is an unconditional branch. Can we simply invert the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 // condition and swap destinations:
1300 // beq L1
1301 // b L2
1302 // =>
1303 // bne L2
1304 // b L1
Chris Lattner6017d482007-12-30 23:10:15 +00001305 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001307 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1308 << *BMI);
Chris Lattner6017d482007-12-30 23:10:15 +00001309 BMI->getOperand(0).setMBB(DestBB);
1310 MI->getOperand(0).setMBB(NewDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 MI->getOperand(1).setImm(CC);
1312 return true;
1313 }
1314 }
1315 }
1316
1317 if (NeedSplit) {
1318 SplitBlockBeforeInstr(MI);
Bob Wilsond6985d52009-05-12 17:35:29 +00001319 // No need for the branch to the next block. We're adding an unconditional
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 // branch to the destination.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001321 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 BBSizes[MBB->getNumber()] -= delta;
1323 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1324 AdjustBBOffsetsAfter(SplitBB, -delta);
1325 MBB->back().eraseFromParent();
1326 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1327 }
1328 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilsonec92b492009-05-12 17:09:30 +00001329
Chris Lattner2c6014b2009-08-23 06:49:22 +00001330 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1331 << " also invert condition and change dest. to BB#"
1332 << NextBB->getNumber() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333
1334 // Insert a new conditional branch and a new unconditional branch.
1335 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001336 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1337 TII->get(MI->getOpcode()))
1338 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 Br.MI = &MBB->back();
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001340 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesene8a10c42009-02-13 02:25:56 +00001341 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001342 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1344 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1345
1346 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001347 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 MI->eraseFromParent();
1349
1350 // The net size change is an addition of one unconditional branch.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001351 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 AdjustBBOffsetsAfter(MBB, delta);
1353 return true;
1354}
1355
1356/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng94958142009-08-11 21:11:32 +00001357/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1358/// to do this if tBfar is not used.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359bool ARMConstantIslands::UndoLRSpillRestore() {
1360 bool MadeChange = false;
1361 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1362 MachineInstr *MI = PushPopMIs[i];
Evan Chenga9a6b652009-10-01 20:54:53 +00001363 // First two operands are predicates, the third is a zero since there
1364 // is no writeback.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Chenga9a6b652009-10-01 20:54:53 +00001366 MI->getOperand(3).getReg() == ARM::PC &&
1367 MI->getNumExplicitOperands() == 4) {
Dale Johannesene8a10c42009-02-13 02:25:56 +00001368 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 MI->eraseFromParent();
1370 MadeChange = true;
1371 }
1372 }
1373 return MadeChange;
1374}
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001375
Evan Chenga441c1a2009-08-14 00:32:16 +00001376bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1377 bool MadeChange = false;
1378
1379 // Shrink ADR and LDR from constantpool.
1380 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1381 CPUser &U = CPUsers[i];
1382 unsigned Opcode = U.MI->getOpcode();
1383 unsigned NewOpc = 0;
1384 unsigned Scale = 1;
1385 unsigned Bits = 0;
1386 switch (Opcode) {
1387 default: break;
1388 case ARM::t2LEApcrel:
1389 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1390 NewOpc = ARM::tLEApcrel;
1391 Bits = 8;
1392 Scale = 4;
1393 }
1394 break;
1395 case ARM::t2LDRpci:
1396 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1397 NewOpc = ARM::tLDRpci;
1398 Bits = 8;
1399 Scale = 4;
1400 }
1401 break;
1402 }
1403
1404 if (!NewOpc)
1405 continue;
1406
1407 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1408 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1409 // FIXME: Check if offset is multiple of scale if scale is not 4.
1410 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1411 U.MI->setDesc(TII->get(NewOpc));
1412 MachineBasicBlock *MBB = U.MI->getParent();
1413 BBSizes[MBB->getNumber()] -= 2;
1414 AdjustBBOffsetsAfter(MBB, -2);
1415 ++NumT2CPShrunk;
1416 MadeChange = true;
1417 }
1418 }
1419
Evan Chenga441c1a2009-08-14 00:32:16 +00001420 MadeChange |= OptimizeThumb2Branches(MF);
Evan Chengf7b61a12009-08-14 18:31:44 +00001421 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga441c1a2009-08-14 00:32:16 +00001422 return MadeChange;
1423}
1424
1425bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Chengf7b61a12009-08-14 18:31:44 +00001426 bool MadeChange = false;
1427
1428 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1429 ImmBranch &Br = ImmBranches[i];
1430 unsigned Opcode = Br.MI->getOpcode();
1431 unsigned NewOpc = 0;
1432 unsigned Scale = 1;
1433 unsigned Bits = 0;
1434 switch (Opcode) {
1435 default: break;
1436 case ARM::t2B:
1437 NewOpc = ARM::tB;
1438 Bits = 11;
1439 Scale = 2;
1440 break;
1441 case ARM::t2Bcc:
1442 NewOpc = ARM::tBcc;
1443 Bits = 8;
1444 Scale = 2;
1445 break;
1446 }
1447 if (!NewOpc)
1448 continue;
1449
1450 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1451 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1452 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1453 Br.MI->setDesc(TII->get(NewOpc));
1454 MachineBasicBlock *MBB = Br.MI->getParent();
1455 BBSizes[MBB->getNumber()] -= 2;
1456 AdjustBBOffsetsAfter(MBB, -2);
1457 ++NumT2BrShrunk;
1458 MadeChange = true;
1459 }
1460 }
1461
1462 return MadeChange;
Evan Chenga441c1a2009-08-14 00:32:16 +00001463}
1464
1465
1466/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1467/// jumptables when it's possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001468bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1469 bool MadeChange = false;
1470
1471 // FIXME: After the tables are shrunk, can we get rid some of the
1472 // constantpool tables?
1473 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1474 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1475 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1476 MachineInstr *MI = T2JumpTables[i];
1477 const TargetInstrDesc &TID = MI->getDesc();
1478 unsigned NumOps = TID.getNumOperands();
1479 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1480 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1481 unsigned JTI = JTOP.getIndex();
1482 assert(JTI < JT.size());
1483
1484 bool ByteOk = true;
1485 bool HalfWordOk = true;
1486 unsigned JTOffset = GetOffsetOf(MI) + 4;
1487 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1488 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1489 MachineBasicBlock *MBB = JTBBs[j];
1490 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Chenge12c92d2009-07-29 23:20:20 +00001491 // Negative offset is not ok. FIXME: We should change BB layout to make
1492 // sure all the branches are forward.
Evan Chengb6a03382009-07-31 18:28:05 +00001493 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001494 ByteOk = false;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001495 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001496 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001497 HalfWordOk = false;
1498 if (!ByteOk && !HalfWordOk)
1499 break;
1500 }
1501
1502 if (ByteOk || HalfWordOk) {
1503 MachineBasicBlock *MBB = MI->getParent();
1504 unsigned BaseReg = MI->getOperand(0).getReg();
1505 bool BaseRegKill = MI->getOperand(0).isKill();
1506 if (!BaseRegKill)
1507 continue;
1508 unsigned IdxReg = MI->getOperand(1).getReg();
1509 bool IdxRegKill = MI->getOperand(1).isKill();
1510 MachineBasicBlock::iterator PrevI = MI;
1511 if (PrevI == MBB->begin())
1512 continue;
1513
1514 MachineInstr *AddrMI = --PrevI;
1515 bool OptOk = true;
1516 // Examine the instruction that calculate the jumptable entry address.
1517 // If it's not the one just before the t2BR_JT, we won't delete it, then
1518 // it's not worth doing the optimization.
1519 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1520 const MachineOperand &MO = AddrMI->getOperand(k);
1521 if (!MO.isReg() || !MO.getReg())
1522 continue;
1523 if (MO.isDef() && MO.getReg() != BaseReg) {
1524 OptOk = false;
1525 break;
1526 }
1527 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1528 OptOk = false;
1529 break;
1530 }
1531 }
1532 if (!OptOk)
1533 continue;
1534
Evan Chenga441c1a2009-08-14 00:32:16 +00001535 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1536 // to delete it as well.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001537 MachineInstr *LeaMI = --PrevI;
Evan Chenga441c1a2009-08-14 00:32:16 +00001538 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1539 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001540 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng04f40fa2009-08-01 06:13:52 +00001541 OptOk = false;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001542
Evan Cheng04f40fa2009-08-01 06:13:52 +00001543 if (!OptOk)
1544 continue;
1545
1546 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1547 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1548 .addReg(IdxReg, getKillRegState(IdxRegKill))
1549 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1550 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1551 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1552 // is 2-byte aligned. For now, asm printer will fix it up.
1553 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1554 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1555 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1556 OrigSize += TII->GetInstSizeInBytes(MI);
1557
1558 AddrMI->eraseFromParent();
1559 LeaMI->eraseFromParent();
1560 MI->eraseFromParent();
1561
1562 int delta = OrigSize - NewSize;
1563 BBSizes[MBB->getNumber()] -= delta;
1564 AdjustBBOffsetsAfter(MBB, -delta);
1565
1566 ++NumTBs;
1567 MadeChange = true;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001568 }
1569 }
1570
1571 return MadeChange;
1572}