blob: ea64bab79d1ec5b583f0cb1553b62dada32af900 [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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
33using namespace llvm;
34
Evan Chenga441c1a2009-08-14 00:32:16 +000035STATISTIC(NumCPEs, "Number of constpool entries");
36STATISTIC(NumSplit, "Number of uncond branches inserted");
37STATISTIC(NumCBrFixed, "Number of cond branches fixed");
38STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39STATISTIC(NumTBs, "Number of table branches generated");
40STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041
42namespace {
43 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
44 /// requires constant pool entries to be scattered among the instructions
45 /// inside a function. To do this, it completely ignores the normal LLVM
46 /// constant pool; instead, it places constants wherever it feels like with
47 /// special instructions.
48 ///
49 /// The terminology used in this pass includes:
50 /// Islands - Clumps of constants placed in the function.
51 /// Water - Potential places where an island could be formed.
52 /// CPE - A constant pool entry that has been placed somewhere, which
53 /// tracks a list of users.
54 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
56 /// by MBB Number. The two-byte pads required for Thumb alignment are
57 /// counted as part of the following block (i.e., the offset and size for
58 /// a padded block will both be ==2 mod 4).
59 std::vector<unsigned> BBSizes;
Bob Wilsonec92b492009-05-12 17:09:30 +000060
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
62 /// The two-byte pads required for Thumb alignment are counted as part of
63 /// the following block.
64 std::vector<unsigned> BBOffsets;
65
66 /// WaterList - A sorted list of basic blocks where islands could be placed
67 /// (i.e. blocks that don't fall through to the following block, due
68 /// to a return, unreachable, or unconditional branch).
69 std::vector<MachineBasicBlock*> WaterList;
70
71 /// CPUser - One user of a constant pool, keeping the machine instruction
72 /// pointer, the constant pool being referenced, and the max displacement
73 /// allowed from the instruction to the CP.
74 struct CPUser {
75 MachineInstr *MI;
76 MachineInstr *CPEMI;
77 unsigned MaxDisp;
Evan Chengbf2498c2009-07-21 23:56:01 +000078 bool NegOk;
Evan Chengf6e7e692009-07-23 18:27:47 +000079 bool IsSoImm;
80 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
81 bool neg, bool soimm)
82 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 };
Bob Wilsonec92b492009-05-12 17:09:30 +000084
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 /// CPUsers - Keep track of all of the machine instructions that use various
86 /// constant pools and their max displacement.
87 std::vector<CPUser> CPUsers;
Bob Wilsonec92b492009-05-12 17:09:30 +000088
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 /// CPEntry - One per constant pool entry, keeping the machine instruction
90 /// pointer, the constpool index, and the number of CPUser's which
91 /// reference this entry.
92 struct CPEntry {
93 MachineInstr *CPEMI;
94 unsigned CPI;
95 unsigned RefCount;
96 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
97 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
98 };
99
100 /// CPEntries - Keep track of all of the constant pool entry machine
101 /// instructions. For each original constpool index (i.e. those that
102 /// existed upon entry to this pass), it keeps a vector of entries.
103 /// Original elements are cloned as we go along; the clones are
104 /// put in the vector of the original element, but have distinct CPIs.
105 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilsonec92b492009-05-12 17:09:30 +0000106
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 /// ImmBranch - One per immediate branch, keeping the machine instruction
108 /// pointer, conditional or unconditional, the max displacement,
109 /// and (if isCond is true) the corresponding unconditional branch
110 /// opcode.
111 struct ImmBranch {
112 MachineInstr *MI;
113 unsigned MaxDisp : 31;
114 bool isCond : 1;
115 int UncondBr;
116 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
117 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
118 };
119
120 /// ImmBranches - Keep track of all the immediate branch instructions.
121 ///
122 std::vector<ImmBranch> ImmBranches;
123
124 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
125 ///
126 SmallVector<MachineInstr*, 4> PushPopMIs;
127
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000128 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
129 SmallVector<MachineInstr*, 4> T2JumpTables;
130
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 /// HasFarJump - True if any far jump instruction has been emitted during
132 /// the branch fix up pass.
133 bool HasFarJump;
134
135 const TargetInstrInfo *TII;
Evan Cheng04f40fa2009-08-01 06:13:52 +0000136 const ARMSubtarget *STI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 ARMFunctionInfo *AFI;
138 bool isThumb;
Evan Chengf6e7e692009-07-23 18:27:47 +0000139 bool isThumb1;
David Goodwinf6154702009-06-30 18:04:13 +0000140 bool isThumb2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 public:
142 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000143 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000145 virtual bool runOnMachineFunction(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146
147 virtual const char *getPassName() const {
148 return "ARM constant island placement and branch shortening pass";
149 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 private:
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000152 void DoInitialPlacement(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 std::vector<MachineInstr*> &CPEMIs);
154 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000155 void InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 const std::vector<MachineInstr*> &CPEMIs);
157 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
158 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
159 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
160 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
161 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonec92b492009-05-12 17:09:30 +0000162 bool LookForWater(CPUser&U, unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 MachineBasicBlock** NewMBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000164 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 std::vector<MachineBasicBlock*>::iterator IP);
166 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
167 MachineBasicBlock** NewMBB);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000168 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 void RemoveDeadCPEMI(MachineInstr *CPEMI);
170 bool RemoveUnusedCPEntries();
Bob Wilsonec92b492009-05-12 17:09:30 +0000171 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000172 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
173 bool DoDump = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
175 CPUser &U);
176 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000177 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000179 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
180 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
181 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 bool UndoLRSpillRestore();
Evan Chenga441c1a2009-08-14 00:32:16 +0000183 bool OptimizeThumb2Instructions(MachineFunction &MF);
184 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000185 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186
187 unsigned GetOffsetOf(MachineInstr *MI) const;
188 void dumpBBs();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000189 void verify(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 };
191 char ARMConstantIslands::ID = 0;
192}
193
194/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000195void ARMConstantIslands::verify(MachineFunction &MF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 assert(BBOffsets.size() == BBSizes.size());
197 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
198 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengf6e7e692009-07-23 18:27:47 +0000199 if (!isThumb)
200 return;
201#ifndef NDEBUG
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000202 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengf6e7e692009-07-23 18:27:47 +0000203 MBBI != E; ++MBBI) {
204 MachineBasicBlock *MBB = MBBI;
205 if (!MBB->empty() &&
206 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
207 unsigned MBBId = MBB->getNumber();
208 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
209 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 }
211 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000212#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213}
214
215/// print block size and offset information - debugging
216void ARMConstantIslands::dumpBBs() {
217 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000218 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 " size " << BBSizes[J] << "\n";
220 }
221}
222
223/// createARMConstantIslandPass - returns an instance of the constpool
224/// island pass.
225FunctionPass *llvm::createARMConstantIslandPass() {
226 return new ARMConstantIslands();
227}
228
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000229bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
230 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilsonec92b492009-05-12 17:09:30 +0000231
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000232 TII = MF.getTarget().getInstrInfo();
233 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng04f40fa2009-08-01 06:13:52 +0000234 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
235
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 isThumb = AFI->isThumbFunction();
Evan Chengf6e7e692009-07-23 18:27:47 +0000237 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwinf6154702009-06-30 18:04:13 +0000238 isThumb2 = AFI->isThumb2Function();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 HasFarJump = false;
241
242 // Renumber all of the machine basic blocks in the function, guaranteeing that
243 // the numbers agree with the position of the block in the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000244 MF.RenumberBlocks();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245
Evan Chengb6a03382009-07-31 18:28:05 +0000246 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengf6e7e692009-07-23 18:27:47 +0000247 // This is so we can keep exact track of where the alignment padding goes.
248
Evan Chengb6a03382009-07-31 18:28:05 +0000249 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengf6e7e692009-07-23 18:27:47 +0000250 // aligned.
251 AFI->setAlign(isThumb1 ? 1U : 2U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252
253 // Perform the initial placement of the constant pool entries. To start with,
254 // we put them all at the end of the function.
255 std::vector<MachineInstr*> CPEMIs;
256 if (!MCP.isEmpty()) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000257 DoInitialPlacement(MF, CPEMIs);
Evan Chengf6e7e692009-07-23 18:27:47 +0000258 if (isThumb1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 AFI->setAlign(2U);
260 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000261
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 /// The next UID to take is the first unused one.
Evan Chengd3c573a2008-11-08 00:51:41 +0000263 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilsonec92b492009-05-12 17:09:30 +0000264
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 // Do the initial scan of the function, building up information about the
266 // sizes of each block, the location of all the water, and finding all of the
267 // constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000268 InitialFunctionScan(MF, CPEMIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 CPEMIs.clear();
Bob Wilsonec92b492009-05-12 17:09:30 +0000270
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 /// Remove dead constant pool entries.
272 RemoveUnusedCPEntries();
273
274 // Iteratively place constant pool entries and fix up branches until there
275 // is no change.
276 bool MadeChange = false;
Evan Cheng3c05d132009-08-07 07:35:21 +0000277 unsigned NoCPIters = 0, NoBRIters = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 while (true) {
Evan Cheng3c05d132009-08-07 07:35:21 +0000279 bool CPChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000281 CPChange |= HandleConstantPoolUser(MF, i);
282 if (CPChange && ++NoCPIters > 30)
283 llvm_unreachable("Constant Island pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000285
286 bool BRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000288 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
289 if (BRChange && ++NoBRIters > 30)
290 llvm_unreachable("Branch Fix Up pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000292
293 if (!CPChange && !BRChange)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 break;
295 MadeChange = true;
296 }
297
Evan Chenga441c1a2009-08-14 00:32:16 +0000298 // Shrink 32-bit Thumb2 branch, load, and store instructions.
299 if (isThumb2)
300 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng04f40fa2009-08-01 06:13:52 +0000301
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000303 verify(MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
306 // Undo the spill / restore of LR if possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000307 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 MadeChange |= UndoLRSpillRestore();
309
310 BBSizes.clear();
311 BBOffsets.clear();
312 WaterList.clear();
313 CPUsers.clear();
314 CPEntries.clear();
315 ImmBranches.clear();
316 PushPopMIs.clear();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000317 T2JumpTables.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318
319 return MadeChange;
320}
321
322/// DoInitialPlacement - Perform the initial placement of the constant pool
323/// entries. To start with, we put them all at the end of the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000324void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +0000325 std::vector<MachineInstr*> &CPEMIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 // Create the basic block to hold the CPE's.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000327 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
328 MF.push_back(BB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000329
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 // Add all of the constants from the constant pool to the end block, use an
331 // identity mapping of CPI's to CPE's.
332 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000333 MF.getConstantPool()->getConstants();
Bob Wilsonec92b492009-05-12 17:09:30 +0000334
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000335 const TargetData &TD = *MF.getTarget().getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000337 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
339 // we would have to pad them out or something so that instructions stay
340 // aligned.
341 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
342 MachineInstr *CPEMI =
Dale Johannesene8a10c42009-02-13 02:25:56 +0000343 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 .addImm(i).addConstantPoolIndex(i).addImm(Size);
345 CPEMIs.push_back(CPEMI);
346
347 // Add a new CPEntry, but no corresponding CPUser yet.
348 std::vector<CPEntry> CPEs;
349 CPEs.push_back(CPEntry(CPEMI, i));
350 CPEntries.push_back(CPEs);
351 NumCPEs++;
352 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
353 }
354}
355
356/// BBHasFallthrough - Return true if the specified basic block can fallthrough
357/// into the block immediately after it.
358static bool BBHasFallthrough(MachineBasicBlock *MBB) {
359 // Get the next machine basic block in the function.
360 MachineFunction::iterator MBBI = MBB;
361 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
362 return false;
Bob Wilsonec92b492009-05-12 17:09:30 +0000363
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 MachineBasicBlock *NextBB = next(MBBI);
365 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
366 E = MBB->succ_end(); I != E; ++I)
367 if (*I == NextBB)
368 return true;
Bob Wilsonec92b492009-05-12 17:09:30 +0000369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 return false;
371}
372
373/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
374/// look up the corresponding CPEntry.
375ARMConstantIslands::CPEntry
376*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
377 const MachineInstr *CPEMI) {
378 std::vector<CPEntry> &CPEs = CPEntries[CPI];
379 // Number of entries per constpool index should be small, just do a
380 // linear search.
381 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
382 if (CPEs[i].CPEMI == CPEMI)
383 return &CPEs[i];
384 }
385 return NULL;
386}
387
388/// InitialFunctionScan - Do the initial scan of the function, building up
389/// information about the sizes of each block, the location of all the water,
390/// and finding all of the constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000391void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 const std::vector<MachineInstr*> &CPEMIs) {
393 unsigned Offset = 0;
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000394 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 MBBI != E; ++MBBI) {
396 MachineBasicBlock &MBB = *MBBI;
Bob Wilsonec92b492009-05-12 17:09:30 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 // If this block doesn't fall through into the next MBB, then this is
399 // 'water' that a constant pool island could be placed.
400 if (!BBHasFallthrough(&MBB))
401 WaterList.push_back(&MBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000402
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 unsigned MBBSize = 0;
404 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
405 I != E; ++I) {
406 // Add instruction size to MBBSize.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000407 MBBSize += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408
409 int Opc = I->getOpcode();
Chris Lattner5b930372008-01-07 07:27:27 +0000410 if (I->getDesc().isBranch()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 bool isCond = false;
412 unsigned Bits = 0;
413 unsigned Scale = 1;
414 int UOpc = Opc;
415 switch (Opc) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000416 default:
417 continue; // Ignore other JT branches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 case ARM::tBR_JTr:
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000419 // A Thumb1 table jump may involve padding; for the offsets to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 // be right, functions containing these must be 4-byte aligned.
421 AFI->setAlign(2U);
422 if ((Offset+MBBSize)%4 != 0)
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000423 // FIXME: Add a pseudo ALIGN instruction instead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 MBBSize += 2; // padding
425 continue; // Does not get an entry in ImmBranches
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000426 case ARM::t2BR_JT:
427 T2JumpTables.push_back(I);
428 continue; // Does not get an entry in ImmBranches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 case ARM::Bcc:
430 isCond = true;
431 UOpc = ARM::B;
432 // Fallthrough
433 case ARM::B:
434 Bits = 24;
435 Scale = 4;
436 break;
437 case ARM::tBcc:
438 isCond = true;
439 UOpc = ARM::tB;
440 Bits = 8;
441 Scale = 2;
442 break;
443 case ARM::tB:
444 Bits = 11;
445 Scale = 2;
446 break;
David Goodwinf6154702009-06-30 18:04:13 +0000447 case ARM::t2Bcc:
448 isCond = true;
449 UOpc = ARM::t2B;
450 Bits = 20;
451 Scale = 2;
452 break;
453 case ARM::t2B:
454 Bits = 24;
455 Scale = 2;
456 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 }
458
459 // Record this immediate branch.
460 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
461 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
462 }
463
464 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
465 PushPopMIs.push_back(I);
466
Evan Chengf6e7e692009-07-23 18:27:47 +0000467 if (Opc == ARM::CONSTPOOL_ENTRY)
468 continue;
469
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 // Scan the instructions for constant pool operands.
471 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000472 if (I->getOperand(op).isCPI()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 // We found one. The addressing mode tells us the max displacement
474 // from the PC that this instruction permits.
Bob Wilsonec92b492009-05-12 17:09:30 +0000475
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 // Basic size info comes from the TSFlags field.
477 unsigned Bits = 0;
478 unsigned Scale = 1;
Evan Chengbf2498c2009-07-21 23:56:01 +0000479 bool NegOk = false;
Evan Chengf6e7e692009-07-23 18:27:47 +0000480 bool IsSoImm = false;
481
Evan Cheng04f40fa2009-08-01 06:13:52 +0000482 // FIXME: Temporary workaround until I can figure out what's going on.
483 unsigned Slack = T2JumpTables.empty() ? 0 : 4;
Evan Chengf6e7e692009-07-23 18:27:47 +0000484 switch (Opc) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000485 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000486 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengf6e7e692009-07-23 18:27:47 +0000487 break;
488
489 // Taking the address of a CP entry.
490 case ARM::LEApcrel:
491 // This takes a SoImm, which is 8 bit immediate rotated. We'll
492 // pretend the maximum offset is 255 * 4. Since each instruction
493 // 4 byte wide, this is always correct. We'llc heck for other
494 // displacements that fits in a SoImm as well.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 Bits = 8;
Evan Chengf6e7e692009-07-23 18:27:47 +0000496 Scale = 4;
497 NegOk = true;
498 IsSoImm = true;
499 break;
500 case ARM::t2LEApcrel:
501 Bits = 12;
Evan Chengbf2498c2009-07-21 23:56:01 +0000502 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000504 case ARM::tLEApcrel:
505 Bits = 8;
506 Scale = 4;
507 break;
508
509 case ARM::LDR:
510 case ARM::LDRcp:
511 case ARM::t2LDRpci:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 Bits = 12; // +-offset_12
Evan Chengbf2498c2009-07-21 23:56:01 +0000513 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000515
516 case ARM::tLDRpci:
517 case ARM::tLDRcp:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 Bits = 8;
519 Scale = 4; // +(offset_8*4)
520 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000521
522 case ARM::FLDD:
523 case ARM::FLDS:
524 Bits = 8;
525 Scale = 4; // +-(offset_8*4)
526 NegOk = true;
Evan Cheng532cdc52009-06-29 07:51:04 +0000527 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 }
529
530 // Remember that this is a user of a CP entry.
Chris Lattner6017d482007-12-30 23:10:15 +0000531 unsigned CPI = I->getOperand(op).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng04f40fa2009-08-01 06:13:52 +0000533 unsigned MaxOffs = ((1 << Bits)-1) * Scale - Slack;
Evan Chengf6e7e692009-07-23 18:27:47 +0000534 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535
536 // Increment corresponding CPEntry reference count.
537 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
538 assert(CPE && "Cannot find a corresponding CPEntry!");
539 CPE->RefCount++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000540
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 // Instructions can only use one CP entry, don't bother scanning the
542 // rest of the operands.
543 break;
544 }
545 }
546
547 // In thumb mode, if this block is a constpool island, we may need padding
548 // so it's aligned on 4 byte boundary.
549 if (isThumb &&
550 !MBB.empty() &&
551 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
552 (Offset%4) != 0)
553 MBBSize += 2;
554
555 BBSizes.push_back(MBBSize);
556 BBOffsets.push_back(Offset);
557 Offset += MBBSize;
558 }
559}
560
561/// GetOffsetOf - Return the current offset of the specified machine instruction
562/// from the start of the function. This offset changes as stuff is moved
563/// around inside the function.
564unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
565 MachineBasicBlock *MBB = MI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000566
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 // The offset is composed of two things: the sum of the sizes of all MBB's
568 // before this instruction's block, and the offset from the start of the block
569 // it is in.
570 unsigned Offset = BBOffsets[MBB->getNumber()];
571
572 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
573 // alignment padding, and compensate if so.
Bob Wilsonec92b492009-05-12 17:09:30 +0000574 if (isThumb &&
575 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 Offset%4 != 0)
577 Offset += 2;
578
579 // Sum instructions before MI in MBB.
580 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
581 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
582 if (&*I == MI) return Offset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000583 Offset += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 }
585}
586
587/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
588/// ID.
589static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
590 const MachineBasicBlock *RHS) {
591 return LHS->getNumber() < RHS->getNumber();
592}
593
594/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
595/// machine function, it upsets all of the block numbers. Renumber the blocks
596/// and update the arrays that parallel this numbering.
597void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
598 // Renumber the MBB's to keep them consequtive.
599 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000600
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 // Insert a size into BBSizes to align it properly with the (newly
602 // renumbered) block numbers.
603 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
604
605 // Likewise for BBOffsets.
606 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000607
608 // Next, update WaterList. Specifically, we need to add NewMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 // available water after it.
610 std::vector<MachineBasicBlock*>::iterator IP =
611 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
612 CompareMBBNumbers);
613 WaterList.insert(IP, NewBB);
614}
615
616
617/// Split the basic block containing MI into two blocks, which are joined by
618/// an unconditional branch. Update datastructures and renumber blocks to
619/// account for this change and returns the newly created block.
620MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
621 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman221a4372008-07-07 23:14:23 +0000622 MachineFunction &MF = *OrigBB->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623
624 // Create a new MBB for the code after the OrigBB.
Bob Wilsonec92b492009-05-12 17:09:30 +0000625 MachineBasicBlock *NewBB =
626 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman221a4372008-07-07 23:14:23 +0000628 MF.insert(MBBI, NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000629
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 // Splice the instructions starting with MI over to NewBB.
631 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilsonec92b492009-05-12 17:09:30 +0000632
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 // Add an unconditional branch from OrigBB to NewBB.
634 // Note the new unconditional branch is not being recorded.
Dale Johannesene8a10c42009-02-13 02:25:56 +0000635 // There doesn't seem to be meaningful DebugInfo available; this doesn't
636 // correspond to anything in the source.
Evan Cheng451192e2009-07-07 01:16:41 +0000637 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
638 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 NumSplit++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000640
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 // Update the CFG. All succs of OrigBB are now succs of NewBB.
642 while (!OrigBB->succ_empty()) {
643 MachineBasicBlock *Succ = *OrigBB->succ_begin();
644 OrigBB->removeSuccessor(Succ);
645 NewBB->addSuccessor(Succ);
Bob Wilsonec92b492009-05-12 17:09:30 +0000646
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 // This pass should be run after register allocation, so there should be no
648 // PHI nodes to update.
649 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
650 && "PHI nodes should be eliminated by now!");
651 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 // OrigBB branches to NewBB.
654 OrigBB->addSuccessor(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 // Update internal data structures to account for the newly inserted MBB.
657 // This is almost the same as UpdateForInsertedWaterBlock, except that
658 // the Water goes after OrigBB, not NewBB.
Dan Gohman221a4372008-07-07 23:14:23 +0000659 MF.RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000660
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 // Insert a size into BBSizes to align it properly with the (newly
662 // renumbered) block numbers.
663 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000664
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 // Likewise for BBOffsets.
666 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
667
Bob Wilsonec92b492009-05-12 17:09:30 +0000668 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 // available water after it (but not if it's already there, which happens
670 // when splitting before a conditional branch that is followed by an
671 // unconditional branch - in that case we want to insert NewBB).
672 std::vector<MachineBasicBlock*>::iterator IP =
673 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
674 CompareMBBNumbers);
675 MachineBasicBlock* WaterBB = *IP;
676 if (WaterBB == OrigBB)
677 WaterList.insert(next(IP), NewBB);
678 else
679 WaterList.insert(IP, OrigBB);
680
681 // Figure out how large the first NewMBB is. (It cannot
682 // contain a constpool_entry or tablejump.)
683 unsigned NewBBSize = 0;
684 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
685 I != E; ++I)
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000686 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilsonec92b492009-05-12 17:09:30 +0000687
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 unsigned OrigBBI = OrigBB->getNumber();
689 unsigned NewBBI = NewBB->getNumber();
690 // Set the size of NewBB in BBSizes.
691 BBSizes[NewBBI] = NewBBSize;
Bob Wilsonec92b492009-05-12 17:09:30 +0000692
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 // We removed instructions from UserMBB, subtract that off from its size.
694 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng04f40fa2009-08-01 06:13:52 +0000695 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 BBSizes[OrigBBI] -= NewBBSize - delta;
697
698 // ...and adjust BBOffsets for NewBB accordingly.
699 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
700
701 // All BBOffsets following these blocks must be modified.
702 AdjustBBOffsetsAfter(NewBB, delta);
703
704 return NewBB;
705}
706
707/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilsonec92b492009-05-12 17:09:30 +0000708/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709/// constant pool entry).
Bob Wilsonec92b492009-05-12 17:09:30 +0000710bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000711 unsigned TrialOffset, unsigned MaxDisp,
712 bool NegativeOK, bool IsSoImm) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000713 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
714 // purposes of the displacement computation; compensate for that here.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 // Effectively, the valid range of displacements is 2 bytes smaller for such
716 // references.
717 if (isThumb && UserOffset%4 !=0)
718 UserOffset -= 2;
719 // CPEs will be rounded up to a multiple of 4.
720 if (isThumb && TrialOffset%4 != 0)
721 TrialOffset += 2;
722
723 if (UserOffset <= TrialOffset) {
724 // User before the Trial.
Evan Chengf6e7e692009-07-23 18:27:47 +0000725 if (TrialOffset - UserOffset <= MaxDisp)
726 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000727 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728 } else if (NegativeOK) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000729 if (UserOffset - TrialOffset <= MaxDisp)
730 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000731 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 }
733 return false;
734}
735
736/// WaterIsInRange - Returns true if a CPE placed after the specified
737/// Water (a basic block) will be in range for the specific MI.
738
739bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000740 MachineBasicBlock* Water, CPUser &U) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 unsigned MaxDisp = U.MaxDisp;
Bob Wilsonec92b492009-05-12 17:09:30 +0000742 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 BBSizes[Water->getNumber()];
744
745 // If the CPE is to be inserted before the instruction, that will raise
746 // the offset of the instruction. (Currently applies only to ARM, so
747 // no alignment compensation attempted here.)
748 if (CPEOffset < UserOffset)
749 UserOffset += U.CPEMI->getOperand(2).getImm();
750
Evan Chengf6e7e692009-07-23 18:27:47 +0000751 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752}
753
754/// CPEIsInRange - Returns true if the distance between specific MI and
755/// specific ConstPool entry instruction can fit in MI's displacement field.
756bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000757 MachineInstr *CPEMI, unsigned MaxDisp,
758 bool NegOk, bool DoDump) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 unsigned CPEOffset = GetOffsetOf(CPEMI);
760 assert(CPEOffset%4 == 0 && "Misaligned CPE");
761
762 if (DoDump) {
763 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
764 << " max delta=" << MaxDisp
765 << " insn address=" << UserOffset
766 << " CPE address=" << CPEOffset
767 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
768 }
769
Evan Chengbf2498c2009-07-21 23:56:01 +0000770 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771}
772
Evan Cheng10361732009-01-28 00:53:34 +0000773#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
775/// unconditionally branches to its only successor.
776static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
777 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
778 return false;
779
780 MachineBasicBlock *Succ = *MBB->succ_begin();
781 MachineBasicBlock *Pred = *MBB->pred_begin();
782 MachineInstr *PredMI = &Pred->back();
David Goodwinf6154702009-06-30 18:04:13 +0000783 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
784 || PredMI->getOpcode() == ARM::t2B)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 return PredMI->getOperand(0).getMBB() == Succ;
786 return false;
787}
Evan Cheng10361732009-01-28 00:53:34 +0000788#endif // NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789
Bob Wilsonec92b492009-05-12 17:09:30 +0000790void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791 int delta) {
792 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengf6e7e692009-07-23 18:27:47 +0000793 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
794 i < e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 BBOffsets[i] += delta;
796 // If some existing blocks have padding, adjust the padding as needed, a
797 // bit tricky. delta can be negative so don't use % on that.
Evan Chengf6e7e692009-07-23 18:27:47 +0000798 if (!isThumb)
799 continue;
800 MachineBasicBlock *MBB = MBBI;
801 if (!MBB->empty()) {
802 // Constant pool entries require padding.
803 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng275468a2009-08-11 07:36:14 +0000804 unsigned OldOffset = BBOffsets[i] - delta;
805 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000806 // add new padding
807 BBSizes[i] += 2;
808 delta += 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000809 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000810 // remove existing padding
Evan Cheng275468a2009-08-11 07:36:14 +0000811 BBSizes[i] -= 2;
Evan Chengf6e7e692009-07-23 18:27:47 +0000812 delta -= 2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000815 // Thumb1 jump tables require padding. They should be at the end;
816 // following unconditional branches are removed by AnalyzeBranch.
Evan Chenga609c1d2009-07-24 18:20:44 +0000817 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000818 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng275468a2009-08-11 07:36:14 +0000819 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
820 unsigned OldMIOffset = NewMIOffset - delta;
821 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000822 // remove existing padding
823 BBSizes[i] -= 2;
824 delta -= 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000825 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000826 // add new padding
827 BBSizes[i] += 2;
828 delta += 2;
829 }
830 }
831 if (delta==0)
832 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000834 MBBI = next(MBBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
836}
837
838/// DecrementOldEntry - find the constant pool entry with index CPI
839/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilsonec92b492009-05-12 17:09:30 +0000840/// becomes 0 remove the entry and instruction. Returns true if we removed
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841/// the entry, false if we didn't.
842
843bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
844 // Find the old entry. Eliminate it if it is no longer used.
845 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
846 assert(CPE && "Unexpected!");
847 if (--CPE->RefCount == 0) {
848 RemoveDeadCPEMI(CPEMI);
849 CPE->CPEMI = NULL;
850 NumCPEs--;
851 return true;
852 }
853 return false;
854}
855
856/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
857/// if not, see if an in-range clone of the CPE is in range, and if so,
858/// change the data structures so the user references the clone. Returns:
859/// 0 = no existing entry found
860/// 1 = entry found, and there were no code insertions or deletions
861/// 2 = entry found, and there were code insertions or deletions
862int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
863{
864 MachineInstr *UserMI = U.MI;
865 MachineInstr *CPEMI = U.CPEMI;
866
867 // Check to see if the CPE is already in-range.
Evan Chengbf2498c2009-07-21 23:56:01 +0000868 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 DOUT << "In range\n";
870 return 1;
871 }
872
873 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner6017d482007-12-30 23:10:15 +0000874 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 std::vector<CPEntry> &CPEs = CPEntries[CPI];
876 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
877 // We already tried this one
878 if (CPEs[i].CPEMI == CPEMI)
879 continue;
880 // Removing CPEs can leave empty entries, skip
881 if (CPEs[i].CPEMI == NULL)
882 continue;
Evan Chengbf2498c2009-07-21 23:56:01 +0000883 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
885 // Point the CPUser node to the replacement
886 U.CPEMI = CPEs[i].CPEMI;
887 // Change the CPI in the instruction operand to refer to the clone.
888 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000889 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +0000890 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 break;
892 }
893 // Adjust the refcount of the clone...
894 CPEs[i].RefCount++;
895 // ...and the original. If we didn't remove the old entry, none of the
896 // addresses changed, so we don't need another pass.
897 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
898 }
899 }
900 return 0;
901}
902
903/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
904/// the specific unconditional branch instruction.
905static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwinf6154702009-06-30 18:04:13 +0000906 switch (Opc) {
907 case ARM::tB:
908 return ((1<<10)-1)*2;
909 case ARM::t2B:
910 return ((1<<23)-1)*2;
911 default:
912 break;
913 }
Jim Grosbach770d7182009-08-11 15:33:49 +0000914
David Goodwinf6154702009-06-30 18:04:13 +0000915 return ((1<<23)-1)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916}
917
918/// AcceptWater - Small amount of common code factored out of the following.
919
Bob Wilsonec92b492009-05-12 17:09:30 +0000920MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 std::vector<MachineBasicBlock*>::iterator IP) {
922 DOUT << "found water in range\n";
923 // Remove the original WaterList entry; we want subsequent
924 // insertions in this vicinity to go after the one we're
925 // about to insert. This considerably reduces the number
926 // of times we have to move the same CPE more than once.
927 WaterList.erase(IP);
928 // CPE goes before following block (NewMBB).
929 return next(MachineFunction::iterator(WaterBB));
930}
931
932/// LookForWater - look for an existing entry in the WaterList in which
933/// we can place the CPE referenced from U so it's within range of U's MI.
934/// Returns true if found, false if not. If it returns true, *NewMBB
935/// is set to the WaterList entry.
Evan Chengf6e7e692009-07-23 18:27:47 +0000936/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937/// water that will not introduce padding to water that will; within each
938/// group, prefer the water that's farthest away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
940 MachineBasicBlock** NewMBB) {
941 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
942 MachineBasicBlock* WaterBBThatWouldPad = NULL;
943 if (!WaterList.empty()) {
944 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengf6e7e692009-07-23 18:27:47 +0000945 B = WaterList.begin();; --IP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 MachineBasicBlock* WaterBB = *IP;
947 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000948 unsigned WBBId = WaterBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 if (isThumb &&
Evan Chengf6e7e692009-07-23 18:27:47 +0000950 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 // This is valid Water, but would introduce padding. Remember
952 // it in case we don't find any Water that doesn't do this.
953 if (!WaterBBThatWouldPad) {
954 WaterBBThatWouldPad = WaterBB;
955 IPThatWouldPad = IP;
956 }
957 } else {
958 *NewMBB = AcceptWater(WaterBB, IP);
959 return true;
960 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000961 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 if (IP == B)
963 break;
964 }
965 }
966 if (isThumb && WaterBBThatWouldPad) {
967 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
968 return true;
969 }
970 return false;
971}
972
Bob Wilsonec92b492009-05-12 17:09:30 +0000973/// CreateNewWater - No existing WaterList entry will work for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
975/// block is used if in range, and the conditional branch munged so control
976/// flow is correct. Otherwise the block is split to create a hole with an
977/// unconditional branch around it. In either case *NewMBB is set to a
978/// block following which the new island can be inserted (the WaterList
979/// is not adjusted).
980
Bob Wilsonec92b492009-05-12 17:09:30 +0000981void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 unsigned UserOffset, MachineBasicBlock** NewMBB) {
983 CPUser &U = CPUsers[CPUserIndex];
984 MachineInstr *UserMI = U.MI;
985 MachineInstr *CPEMI = U.CPEMI;
986 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000987 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 BBSizes[UserMBB->getNumber()];
989 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
990
991 // If the use is at the end of the block, or the end of the block
992 // is within range, make new water there. (The addition below is
Evan Chengf6e7e692009-07-23 18:27:47 +0000993 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
994 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 // inside OffsetIsInRange.
Bob Wilsonec92b492009-05-12 17:09:30 +0000996 // If the block ends in an unconditional branch already, it is water,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 // and is known to be out of range, so we'll always be adding a branch.)
998 if (&UserMBB->back() == UserMI ||
Evan Chengf6e7e692009-07-23 18:27:47 +0000999 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1000 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 DOUT << "Split at end of block\n";
1002 if (&UserMBB->back() == UserMI)
1003 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1004 *NewMBB = next(MachineFunction::iterator(UserMBB));
1005 // Add an unconditional branch from UserMBB to fallthrough block.
1006 // Record it for branch lengthening; this new branch will not get out of
1007 // range, but if the preceding conditional branch is out of range, the
1008 // targets will be exchanged, and the altered branch may be out of
1009 // range, so the machinery has to know about it.
David Goodwinf6154702009-06-30 18:04:13 +00001010 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesene8a10c42009-02-13 02:25:56 +00001011 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1012 TII->get(UncondBr)).addMBB(*NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilsonec92b492009-05-12 17:09:30 +00001014 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 MaxDisp, false, UncondBr));
Evan Chengf6e7e692009-07-23 18:27:47 +00001016 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 BBSizes[UserMBB->getNumber()] += delta;
1018 AdjustBBOffsetsAfter(UserMBB, delta);
1019 } else {
1020 // What a big block. Find a place within the block to split it.
Evan Chengf6e7e692009-07-23 18:27:47 +00001021 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 // and constant pool entries are 4 bytes: if instruction I references
1023 // island CPE, and instruction I+1 references CPE', it will
1024 // not work well to put CPE as far forward as possible, since then
1025 // CPE' cannot immediately follow it (that location is 2 bytes
1026 // farther away from I+1 than CPE was from I) and we'd need to create
1027 // a new island. So, we make a first guess, then walk through the
1028 // instructions between the one currently being looked at and the
1029 // possible insertion point, and make sure any other instructions
1030 // that reference CPEs will be able to use the same island area;
1031 // if not, we back up the insertion point.
1032
1033 // The 4 in the following is for the unconditional branch we'll be
Evan Chengf6e7e692009-07-23 18:27:47 +00001034 // inserting (allows for long branch on Thumb1). Alignment of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 // island is handled inside OffsetIsInRange.
1036 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1037 // This could point off the end of the block if we've already got
1038 // constant pool entries following this block; only the last one is
1039 // in the water list. Back past any possible branches (allow for a
1040 // conditional and a maximally long unconditional).
1041 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilsonec92b492009-05-12 17:09:30 +00001042 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengf6e7e692009-07-23 18:27:47 +00001043 (isThumb1 ? 6 : 8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 unsigned EndInsertOffset = BaseInsertOffset +
1045 CPEMI->getOperand(2).getImm();
1046 MachineBasicBlock::iterator MI = UserMI;
1047 ++MI;
1048 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001049 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 Offset < BaseInsertOffset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001051 Offset += TII->GetInstSizeInBytes(MI),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 MI = next(MI)) {
1053 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001054 CPUser &U = CPUsers[CPUIndex];
Bob Wilsonec92b492009-05-12 17:09:30 +00001055 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +00001056 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1057 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1058 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 }
1060 // This is overly conservative, as we don't account for CPEMIs
1061 // being reused within the block, but it doesn't matter much.
1062 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1063 CPUIndex++;
1064 }
1065 }
1066 DOUT << "Split in middle of big block\n";
1067 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1068 }
1069}
1070
1071/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsond6985d52009-05-12 17:35:29 +00001072/// is out-of-range. If so, pick up the constant pool value and move it some
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073/// place in-range. Return true if we changed any addresses (thus must run
1074/// another pass of branch lengthening), false otherwise.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001075bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +00001076 unsigned CPUserIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 CPUser &U = CPUsers[CPUserIndex];
1078 MachineInstr *UserMI = U.MI;
1079 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001080 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 unsigned Size = CPEMI->getOperand(2).getImm();
1082 MachineBasicBlock *NewMBB;
1083 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga441c1a2009-08-14 00:32:16 +00001084 // hardware keeps in the PC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1086
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 // See if the current entry is within range, or there is a clone of it
1088 // in range.
1089 int result = LookForExistingCPEntry(U, UserOffset);
1090 if (result==1) return false;
1091 else if (result==2) return true;
1092
1093 // No existing clone of this CPE is within range.
1094 // We will be generating a new clone. Get a UID for it.
Bob Wilsond6985d52009-05-12 17:35:29 +00001095 unsigned ID = AFI->createConstPoolEntryUId();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096
1097 // Look for water where we can place this CPE. We look for the farthest one
1098 // away that will work. Forward references only for now (although later
1099 // we might find some that are backwards).
1100
1101 if (!LookForWater(U, UserOffset, &NewMBB)) {
1102 // No water found.
1103 DOUT << "No water found\n";
1104 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1105 }
1106
1107 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001108 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1109 MF.insert(NewMBB, NewIsland);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110
1111 // Update internal data structures to account for the newly inserted MBB.
1112 UpdateForInsertedWaterBlock(NewIsland);
1113
1114 // Decrement the old entry, and remove it if refcount becomes 0.
1115 DecrementOldEntry(CPI, CPEMI);
1116
1117 // Now that we have an island to add the CPE to, clone the original CPE and
1118 // add it to the island.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001119 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1120 TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1122 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1123 NumCPEs++;
1124
1125 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1126 // Compensate for .align 2 in thumb mode.
Bob Wilsonec92b492009-05-12 17:09:30 +00001127 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 Size += 2;
1129 // Increase the size of the island block to account for the new entry.
1130 BBSizes[NewIsland->getNumber()] += Size;
1131 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilsonec92b492009-05-12 17:09:30 +00001132
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 // Finally, change the CPI in the instruction operand to be ID.
1134 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001135 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +00001136 UserMI->getOperand(i).setIndex(ID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 break;
1138 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001139
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilsonec92b492009-05-12 17:09:30 +00001141
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 return true;
1143}
1144
1145/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1146/// sizes and offsets of impacted basic blocks.
1147void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1148 MachineBasicBlock *CPEBB = CPEMI->getParent();
1149 unsigned Size = CPEMI->getOperand(2).getImm();
1150 CPEMI->eraseFromParent();
1151 BBSizes[CPEBB->getNumber()] -= Size;
1152 // All succeeding offsets have the current size value added in, fix this.
1153 if (CPEBB->empty()) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001154 // In thumb1 mode, the size of island may be padded by two to compensate for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 // the alignment requirement. Then it will now be 2 when the block is
1156 // empty, so fix this.
1157 // All succeeding offsets have the current size value added in, fix this.
1158 if (BBSizes[CPEBB->getNumber()] != 0) {
1159 Size += BBSizes[CPEBB->getNumber()];
1160 BBSizes[CPEBB->getNumber()] = 0;
1161 }
1162 }
1163 AdjustBBOffsetsAfter(CPEBB, -Size);
1164 // An island has only one predecessor BB and one successor BB. Check if
1165 // this BB's predecessor jumps directly to this BB's successor. This
1166 // shouldn't happen currently.
1167 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1168 // FIXME: remove the empty blocks after all the work is done?
1169}
1170
1171/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1172/// are zero.
1173bool ARMConstantIslands::RemoveUnusedCPEntries() {
1174 unsigned MadeChange = false;
1175 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1176 std::vector<CPEntry> &CPEs = CPEntries[i];
1177 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1178 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1179 RemoveDeadCPEMI(CPEs[j].CPEMI);
1180 CPEs[j].CPEMI = NULL;
1181 MadeChange = true;
1182 }
1183 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001184 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 return MadeChange;
1186}
1187
1188/// BBIsInRange - Returns true if the distance between specific MI and
1189/// specific BB can fit in MI's displacement field.
1190bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1191 unsigned MaxDisp) {
1192 unsigned PCAdj = isThumb ? 4 : 8;
1193 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1194 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1195
1196 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1197 << " from BB#" << MI->getParent()->getNumber()
1198 << " max delta=" << MaxDisp
1199 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1200 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1201
1202 if (BrOffset <= DestOffset) {
1203 // Branch before the Dest.
1204 if (DestOffset-BrOffset <= MaxDisp)
1205 return true;
1206 } else {
1207 if (BrOffset-DestOffset <= MaxDisp)
1208 return true;
1209 }
1210 return false;
1211}
1212
1213/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1214/// away to fit in its displacement field.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001215bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001217 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
1219 // Check to see if the DestBB is already in-range.
1220 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1221 return false;
1222
1223 if (!Br.isCond)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001224 return FixUpUnconditionalBr(MF, Br);
1225 return FixUpConditionalBr(MF, Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226}
1227
1228/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1229/// too far away to fit in its displacement field. If the LR register has been
1230/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsond6985d52009-05-12 17:35:29 +00001231/// Otherwise, add an intermediate branch instruction to a branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001233ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 MachineInstr *MI = Br.MI;
1235 MachineBasicBlock *MBB = MI->getParent();
Evan Chengd6053af2009-08-07 05:45:07 +00001236 if (!isThumb1)
1237 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238
1239 // Use BL to implement far jump.
1240 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner86bb02f2008-01-11 18:10:50 +00001241 MI->setDesc(TII->get(ARM::tBfar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 BBSizes[MBB->getNumber()] += 2;
1243 AdjustBBOffsetsAfter(MBB, 2);
1244 HasFarJump = true;
1245 NumUBrFixed++;
1246
1247 DOUT << " Changed B to long jump " << *MI;
1248
1249 return true;
1250}
1251
1252/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1253/// far away to fit in its displacement field. It is converted to an inverse
1254/// conditional branch + an unconditional branch to the destination.
1255bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001256ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001258 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259
Bob Wilsond6985d52009-05-12 17:35:29 +00001260 // Add an unconditional branch to the destination and invert the branch
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261 // condition to jump over it:
1262 // blt L1
1263 // =>
1264 // bge L2
1265 // b L1
1266 // L2:
Chris Lattnera96056a2007-12-30 20:49:49 +00001267 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 CC = ARMCC::getOppositeCondition(CC);
1269 unsigned CCReg = MI->getOperand(2).getReg();
1270
1271 // If the branch is at the end of its MBB and that has a fall-through block,
1272 // direct the updated conditional branch to the fall-through block. Otherwise,
1273 // split the MBB before the next instruction.
1274 MachineBasicBlock *MBB = MI->getParent();
1275 MachineInstr *BMI = &MBB->back();
1276 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1277
1278 NumCBrFixed++;
1279 if (BMI != MI) {
Dan Gohman221a4372008-07-07 23:14:23 +00001280 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsond6985d52009-05-12 17:35:29 +00001282 // Last MI in the BB is an unconditional branch. Can we simply invert the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 // condition and swap destinations:
1284 // beq L1
1285 // b L2
1286 // =>
1287 // bne L2
1288 // b L1
Chris Lattner6017d482007-12-30 23:10:15 +00001289 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1291 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001292 BMI->getOperand(0).setMBB(DestBB);
1293 MI->getOperand(0).setMBB(NewDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 MI->getOperand(1).setImm(CC);
1295 return true;
1296 }
1297 }
1298 }
1299
1300 if (NeedSplit) {
1301 SplitBlockBeforeInstr(MI);
Bob Wilsond6985d52009-05-12 17:35:29 +00001302 // No need for the branch to the next block. We're adding an unconditional
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 // branch to the destination.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001304 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 BBSizes[MBB->getNumber()] -= delta;
1306 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1307 AdjustBBOffsetsAfter(SplitBB, -delta);
1308 MBB->back().eraseFromParent();
1309 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1310 }
1311 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilsonec92b492009-05-12 17:09:30 +00001312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 DOUT << " Insert B to BB#" << DestBB->getNumber()
1314 << " also invert condition and change dest. to BB#"
1315 << NextBB->getNumber() << "\n";
1316
1317 // Insert a new conditional branch and a new unconditional branch.
1318 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001319 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1320 TII->get(MI->getOpcode()))
1321 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 Br.MI = &MBB->back();
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001323 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesene8a10c42009-02-13 02:25:56 +00001324 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001325 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1327 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1328
1329 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001330 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 MI->eraseFromParent();
1332
1333 // The net size change is an addition of one unconditional branch.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001334 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 AdjustBBOffsetsAfter(MBB, delta);
1336 return true;
1337}
1338
1339/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng94958142009-08-11 21:11:32 +00001340/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1341/// to do this if tBfar is not used.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342bool ARMConstantIslands::UndoLRSpillRestore() {
1343 bool MadeChange = false;
1344 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1345 MachineInstr *MI = PushPopMIs[i];
1346 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng2868cf12009-08-13 06:05:07 +00001347 MI->getOperand(2).getReg() == ARM::PC &&
1348 MI->getNumExplicitOperands() == 3) {
Dale Johannesene8a10c42009-02-13 02:25:56 +00001349 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 MI->eraseFromParent();
1351 MadeChange = true;
1352 }
1353 }
1354 return MadeChange;
1355}
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001356
Evan Chenga441c1a2009-08-14 00:32:16 +00001357bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1358 bool MadeChange = false;
1359
1360 // Shrink ADR and LDR from constantpool.
1361 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1362 CPUser &U = CPUsers[i];
1363 unsigned Opcode = U.MI->getOpcode();
1364 unsigned NewOpc = 0;
1365 unsigned Scale = 1;
1366 unsigned Bits = 0;
1367 switch (Opcode) {
1368 default: break;
1369 case ARM::t2LEApcrel:
1370 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1371 NewOpc = ARM::tLEApcrel;
1372 Bits = 8;
1373 Scale = 4;
1374 }
1375 break;
1376 case ARM::t2LDRpci:
1377 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1378 NewOpc = ARM::tLDRpci;
1379 Bits = 8;
1380 Scale = 4;
1381 }
1382 break;
1383 }
1384
1385 if (!NewOpc)
1386 continue;
1387
1388 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1389 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1390 // FIXME: Check if offset is multiple of scale if scale is not 4.
1391 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1392 U.MI->setDesc(TII->get(NewOpc));
1393 MachineBasicBlock *MBB = U.MI->getParent();
1394 BBSizes[MBB->getNumber()] -= 2;
1395 AdjustBBOffsetsAfter(MBB, -2);
1396 ++NumT2CPShrunk;
1397 MadeChange = true;
1398 }
1399 }
1400
1401 MadeChange |= OptimizeThumb2JumpTables(MF);
1402 MadeChange |= OptimizeThumb2Branches(MF);
1403 return MadeChange;
1404}
1405
1406bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1407 return false;
1408}
1409
1410
1411/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1412/// jumptables when it's possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001413bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1414 bool MadeChange = false;
1415
1416 // FIXME: After the tables are shrunk, can we get rid some of the
1417 // constantpool tables?
1418 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1419 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1420 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1421 MachineInstr *MI = T2JumpTables[i];
1422 const TargetInstrDesc &TID = MI->getDesc();
1423 unsigned NumOps = TID.getNumOperands();
1424 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1425 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1426 unsigned JTI = JTOP.getIndex();
1427 assert(JTI < JT.size());
1428
1429 bool ByteOk = true;
1430 bool HalfWordOk = true;
1431 unsigned JTOffset = GetOffsetOf(MI) + 4;
1432 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1433 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1434 MachineBasicBlock *MBB = JTBBs[j];
1435 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Chenge12c92d2009-07-29 23:20:20 +00001436 // Negative offset is not ok. FIXME: We should change BB layout to make
1437 // sure all the branches are forward.
Evan Chengb6a03382009-07-31 18:28:05 +00001438 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001439 ByteOk = false;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001440 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001441 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001442 HalfWordOk = false;
1443 if (!ByteOk && !HalfWordOk)
1444 break;
1445 }
1446
1447 if (ByteOk || HalfWordOk) {
1448 MachineBasicBlock *MBB = MI->getParent();
1449 unsigned BaseReg = MI->getOperand(0).getReg();
1450 bool BaseRegKill = MI->getOperand(0).isKill();
1451 if (!BaseRegKill)
1452 continue;
1453 unsigned IdxReg = MI->getOperand(1).getReg();
1454 bool IdxRegKill = MI->getOperand(1).isKill();
1455 MachineBasicBlock::iterator PrevI = MI;
1456 if (PrevI == MBB->begin())
1457 continue;
1458
1459 MachineInstr *AddrMI = --PrevI;
1460 bool OptOk = true;
1461 // Examine the instruction that calculate the jumptable entry address.
1462 // If it's not the one just before the t2BR_JT, we won't delete it, then
1463 // it's not worth doing the optimization.
1464 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1465 const MachineOperand &MO = AddrMI->getOperand(k);
1466 if (!MO.isReg() || !MO.getReg())
1467 continue;
1468 if (MO.isDef() && MO.getReg() != BaseReg) {
1469 OptOk = false;
1470 break;
1471 }
1472 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1473 OptOk = false;
1474 break;
1475 }
1476 }
1477 if (!OptOk)
1478 continue;
1479
Evan Chenga441c1a2009-08-14 00:32:16 +00001480 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1481 // to delete it as well.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001482 MachineInstr *LeaMI = --PrevI;
Evan Chenga441c1a2009-08-14 00:32:16 +00001483 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1484 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001485 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng04f40fa2009-08-01 06:13:52 +00001486 OptOk = false;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001487
Evan Cheng04f40fa2009-08-01 06:13:52 +00001488 if (!OptOk)
1489 continue;
1490
1491 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1492 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1493 .addReg(IdxReg, getKillRegState(IdxRegKill))
1494 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1495 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1496 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1497 // is 2-byte aligned. For now, asm printer will fix it up.
1498 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1499 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1500 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1501 OrigSize += TII->GetInstSizeInBytes(MI);
1502
1503 AddrMI->eraseFromParent();
1504 LeaMI->eraseFromParent();
1505 MI->eraseFromParent();
1506
1507 int delta = OrigSize - NewSize;
1508 BBSizes[MBB->getNumber()] -= delta;
1509 AdjustBBOffsetsAfter(MBB, -delta);
1510
1511 ++NumTBs;
1512 MadeChange = true;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001513 }
1514 }
1515
1516 return MadeChange;
1517}