blob: ea64bab79d1ec5b583f0cb1553b62dada32af900 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Evan Chengc99ef082007-02-09 20:54:44 +000030#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033using namespace llvm;
34
Evan Chenga1efbbd2009-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");
Evan Chenga8e29892007-01-19 07:51:42 +000041
42namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000043 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000044 /// requires constant pool entries to be scattered among the instructions
45 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000046 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000047 /// 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 {
Evan Chenga8e29892007-01-19 07:51:42 +000055 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000056 /// 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).
Evan Chenge03cff62007-02-09 23:59:14 +000059 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000060
Dale Johannesen99c49a42007-02-25 00:47:03 +000061 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000062 /// The two-byte pads required for Thumb alignment are counted as part of
63 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000064 std::vector<unsigned> BBOffsets;
65
Evan Chenga8e29892007-01-19 07:51:42 +000066 /// 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).
Evan Chenge03cff62007-02-09 23:59:14 +000069 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000070
Evan Chenga8e29892007-01-19 07:51:42 +000071 /// 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 Cheng5d8f1ca2009-07-21 23:56:01 +000078 bool NegOk;
Evan Chengd3d9d662009-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) {}
Evan Chenga8e29892007-01-19 07:51:42 +000083 };
Bob Wilson84945262009-05-12 17:09:30 +000084
Evan Chenga8e29892007-01-19 07:51:42 +000085 /// CPUsers - Keep track of all of the machine instructions that use various
86 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000087 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000088
Evan Chengc99ef082007-02-09 20:54:44 +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
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000101 /// 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.
Evan Chengc99ef082007-02-09 20:54:44 +0000105 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000106
Evan Chengaf5cbcb2007-01-25 03:12: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;
Evan Chengc2854142007-01-25 23:18:59 +0000113 unsigned MaxDisp : 31;
114 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000115 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000116 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
117 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000118 };
119
Evan Cheng2706f972007-05-16 05:14:06 +0000120 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000121 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000122 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000123
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000124 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
125 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000126 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000127
Evan Cheng5657c012009-07-29 02:18:14 +0000128 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
129 SmallVector<MachineInstr*, 4> T2JumpTables;
130
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000131 /// HasFarJump - True if any far jump instruction has been emitted during
132 /// the branch fix up pass.
133 bool HasFarJump;
134
Evan Chenga8e29892007-01-19 07:51:42 +0000135 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000136 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000137 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000138 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000139 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000140 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000141 public:
Devang Patel19974732007-05-03 01:11:54 +0000142 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000143 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000144
Evan Cheng5657c012009-07-29 02:18:14 +0000145 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000146
147 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000148 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000149 }
Bob Wilson84945262009-05-12 17:09:30 +0000150
Evan Chenga8e29892007-01-19 07:51:42 +0000151 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000152 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000153 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000154 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000155 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000156 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000157 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000158 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000159 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000160 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000161 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000162 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000163 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000164 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000165 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000166 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
167 MachineBasicBlock** NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000168 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000169 void RemoveDeadCPEMI(MachineInstr *CPEMI);
170 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000171 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000172 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
173 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000174 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000175 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000176 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000177 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000178 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-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);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000182 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000183 bool OptimizeThumb2Instructions(MachineFunction &MF);
184 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000185 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000186
Evan Chenga8e29892007-01-19 07:51:42 +0000187 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000188 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000189 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000190 };
Devang Patel19974732007-05-03 01:11:54 +0000191 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000192}
193
Dale Johannesen8593e412007-04-29 19:19:30 +0000194/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000195void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +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 Chengd3d9d662009-07-23 18:27:47 +0000199 if (!isThumb)
200 return;
201#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000202 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-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));
Dale Johannesen8593e412007-04-29 19:19:30 +0000210 }
211 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000212#endif
Dale Johannesen8593e412007-04-29 19:19:30 +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 Wilson84945262009-05-12 17:09:30 +0000218 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000219 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000220 }
221}
222
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000223/// createARMConstantIslandPass - returns an instance of the constpool
224/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000225FunctionPass *llvm::createARMConstantIslandPass() {
226 return new ARMConstantIslands();
227}
228
Evan Cheng5657c012009-07-29 02:18:14 +0000229bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
230 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000231
Evan Cheng5657c012009-07-29 02:18:14 +0000232 TII = MF.getTarget().getInstrInfo();
233 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000234 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
235
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000236 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000237 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000238 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000239
240 HasFarJump = false;
241
Evan Chenga8e29892007-01-19 07:51:42 +0000242 // 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 Cheng5657c012009-07-29 02:18:14 +0000244 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000245
Evan Chengd26b14c2009-07-31 18:28:05 +0000246 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000247 // This is so we can keep exact track of where the alignment padding goes.
248
Evan Chengd26b14c2009-07-31 18:28:05 +0000249 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000250 // aligned.
251 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000252
Evan Chenga8e29892007-01-19 07:51:42 +0000253 // Perform the initial placement of the constant pool entries. To start with,
254 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000255 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000256 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000257 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000258 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000259 AFI->setAlign(2U);
260 }
Bob Wilson84945262009-05-12 17:09:30 +0000261
Evan Chenga8e29892007-01-19 07:51:42 +0000262 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000263 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000264
Evan Chenga8e29892007-01-19 07:51:42 +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 Cheng5657c012009-07-29 02:18:14 +0000268 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000269 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000270
Evan Chenged884f32007-04-03 23:39:48 +0000271 /// Remove dead constant pool entries.
272 RemoveUnusedCPEntries();
273
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000274 // Iteratively place constant pool entries and fix up branches until there
275 // is no change.
276 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000277 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000278 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000279 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000280 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000281 CPChange |= HandleConstantPoolUser(MF, i);
282 if (CPChange && ++NoCPIters > 30)
283 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000284 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000285
286 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000287 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-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!");
Evan Cheng82020102007-07-10 22:00:16 +0000291 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000292
293 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000294 break;
295 MadeChange = true;
296 }
Evan Chenged884f32007-04-03 23:39:48 +0000297
Evan Chenga1efbbd2009-08-14 00:32:16 +0000298 // Shrink 32-bit Thumb2 branch, load, and store instructions.
299 if (isThumb2)
300 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000301
Dale Johannesen8593e412007-04-29 19:19:30 +0000302 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000303 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000304
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000305 // 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 Cheng5657c012009-07-29 02:18:14 +0000307 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000308 MadeChange |= UndoLRSpillRestore();
309
Evan Chenga8e29892007-01-19 07:51:42 +0000310 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000311 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000312 WaterList.clear();
313 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000314 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000315 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000316 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000317 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000318
319 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000320}
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 Cheng5657c012009-07-29 02:18:14 +0000324void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000325 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000326 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000327 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
328 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000329
Evan Chenga8e29892007-01-19 07:51:42 +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 Cheng5657c012009-07-29 02:18:14 +0000333 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000334
Evan Cheng5657c012009-07-29 02:18:14 +0000335 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000336 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000337 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +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 Johannesenb6728402009-02-13 02:25:56 +0000343 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000344 .addImm(i).addConstantPoolIndex(i).addImm(Size);
345 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000346
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";
Evan Chenga8e29892007-01-19 07:51:42 +0000353 }
354}
355
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000356/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000357/// 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 Wilson84945262009-05-12 17:09:30 +0000363
Evan Chenga8e29892007-01-19 07:51:42 +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 Wilson84945262009-05-12 17:09:30 +0000369
Evan Chenga8e29892007-01-19 07:51:42 +0000370 return false;
371}
372
Evan Chengc99ef082007-02-09 20:54:44 +0000373/// 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
Evan Chenga8e29892007-01-19 07:51:42 +0000388/// 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 Cheng5657c012009-07-29 02:18:14 +0000391void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000392 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000393 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000394 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000395 MBBI != E; ++MBBI) {
396 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000397
Evan Chenga8e29892007-01-19 07:51:42 +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 Wilson84945262009-05-12 17:09:30 +0000402
Evan Chenga8e29892007-01-19 07:51:42 +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 Geoffray52e724a2008-04-16 20:10:13 +0000407 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000408
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000409 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000410 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000411 bool isCond = false;
412 unsigned Bits = 0;
413 unsigned Scale = 1;
414 int UOpc = Opc;
415 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000416 default:
417 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000418 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000419 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000420 // be right, functions containing these must be 4-byte aligned.
421 AFI->setAlign(2U);
422 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000423 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000424 MBBSize += 2; // padding
425 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000426 case ARM::t2BR_JT:
427 T2JumpTables.push_back(I);
428 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12: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 Goodwin5e47a9a2009-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;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000457 }
Evan Chengb43216e2007-02-01 10:16:15 +0000458
459 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000460 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000461 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000462 }
463
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000464 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
465 PushPopMIs.push_back(I);
466
Evan Chengd3d9d662009-07-23 18:27:47 +0000467 if (Opc == ARM::CONSTPOOL_ENTRY)
468 continue;
469
Evan Chenga8e29892007-01-19 07:51:42 +0000470 // Scan the instructions for constant pool operands.
471 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000472 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000473 // We found one. The addressing mode tells us the max displacement
474 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000475
Evan Chenga8e29892007-01-19 07:51:42 +0000476 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000477 unsigned Bits = 0;
478 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000479 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000480 bool IsSoImm = false;
481
Evan Cheng25f7cfc2009-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 Chengd3d9d662009-07-23 18:27:47 +0000484 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000485 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000486 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-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.
Evan Chengb43216e2007-02-01 10:16:15 +0000495 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000496 Scale = 4;
497 NegOk = true;
498 IsSoImm = true;
499 break;
500 case ARM::t2LEApcrel:
501 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000502 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000503 break;
Evan Chengd3d9d662009-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:
Evan Cheng556f33c2007-02-01 20:44:52 +0000512 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000513 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000514 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000515
516 case ARM::tLDRpci:
517 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000518 Bits = 8;
519 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000520 break;
Evan Chengd3d9d662009-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 Cheng055b0312009-06-29 07:51:04 +0000527 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000528 }
Evan Chengb43216e2007-02-01 10:16:15 +0000529
Evan Chenga8e29892007-01-19 07:51:42 +0000530 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000531 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000532 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000533 unsigned MaxOffs = ((1 << Bits)-1) * Scale - Slack;
Evan Chengd3d9d662009-07-23 18:27:47 +0000534 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +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 Wilson84945262009-05-12 17:09:30 +0000540
Evan Chenga8e29892007-01-19 07:51:42 +0000541 // Instructions can only use one CP entry, don't bother scanning the
542 // rest of the operands.
543 break;
544 }
545 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000546
Dale Johannesen8593e412007-04-29 19:19:30 +0000547 // In thumb mode, if this block is a constpool island, we may need padding
548 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000549 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000550 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000551 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
552 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000553 MBBSize += 2;
554
Evan Chenga8e29892007-01-19 07:51:42 +0000555 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000556 BBOffsets.push_back(Offset);
557 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000558 }
559}
560
Evan Chenga8e29892007-01-19 07:51:42 +0000561/// 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 Wilson84945262009-05-12 17:09:30 +0000566
Evan Chenga8e29892007-01-19 07:51:42 +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.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000570 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000571
Dale Johannesen8593e412007-04-29 19:19:30 +0000572 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
573 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000574 if (isThumb &&
575 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000576 Offset%4 != 0)
577 Offset += 2;
578
Evan Chenga8e29892007-01-19 07:51:42 +0000579 // 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 Geoffray52e724a2008-04-16 20:10:13 +0000583 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +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 Wilson84945262009-05-12 17:09:30 +0000600
Evan Chenga8e29892007-01-19 07:51:42 +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);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000604
605 // Likewise for BBOffsets.
606 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000607
608 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000609 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000610 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000611 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
Evan Cheng0c615842007-01-31 02:22:22 +0000619/// account for this change and returns the newly created block.
620MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000621 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000622 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000623
624 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000625 MachineBasicBlock *NewBB =
626 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000627 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000628 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000629
Evan Chenga8e29892007-01-19 07:51:42 +0000630 // Splice the instructions starting with MI over to NewBB.
631 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000632
Evan Chenga8e29892007-01-19 07:51:42 +0000633 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000634 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-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 Cheng58541fd2009-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);
Evan Chenga8e29892007-01-19 07:51:42 +0000639 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000640
Evan Chenga8e29892007-01-19 07:51:42 +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 Wilson84945262009-05-12 17:09:30 +0000646
Evan Chenga8e29892007-01-19 07:51:42 +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 Wilson84945262009-05-12 17:09:30 +0000652
Evan Chenga8e29892007-01-19 07:51:42 +0000653 // OrigBB branches to NewBB.
654 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000655
Evan Chenga8e29892007-01-19 07:51:42 +0000656 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000657 // This is almost the same as UpdateForInsertedWaterBlock, except that
658 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000659 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000660
Dale Johannesen88e37ae2007-02-23 05:02:36 +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 Wilson84945262009-05-12 17:09:30 +0000664
Dale Johannesen99c49a42007-02-25 00:47:03 +0000665 // Likewise for BBOffsets.
666 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
667
Bob Wilson84945262009-05-12 17:09:30 +0000668 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +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
Dale Johannesen8593e412007-04-29 19:19:30 +0000681 // Figure out how large the first NewMBB is. (It cannot
682 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000683 unsigned NewBBSize = 0;
684 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
685 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000686 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000687
Dale Johannesen99c49a42007-02-25 00:47:03 +0000688 unsigned OrigBBI = OrigBB->getNumber();
689 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000690 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000691 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000692
Evan Chenga8e29892007-01-19 07:51:42 +0000693 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000694 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000695 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +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);
Evan Cheng0c615842007-01-31 02:22:22 +0000703
704 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000705}
706
Dale Johannesen8593e412007-04-29 19:19:30 +0000707/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000708/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000709/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000710bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000711 unsigned TrialOffset, unsigned MaxDisp,
712 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-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.
Dale Johannesen8593e412007-04-29 19:19:30 +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
Dale Johannesen99c49a42007-02-25 00:47:03 +0000723 if (UserOffset <= TrialOffset) {
724 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000725 if (TrialOffset - UserOffset <= MaxDisp)
726 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000727 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000728 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000729 if (UserOffset - TrialOffset <= MaxDisp)
730 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000731 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000732 }
733 return false;
734}
735
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000736/// 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 Cheng5d8f1ca2009-07-21 23:56:01 +0000740 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000741 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000742 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000743 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000744
Dale Johannesend959aa42007-04-02 20:31:06 +0000745 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000746 // the offset of the instruction. (Currently applies only to ARM, so
747 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000748 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000749 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000750
Evan Chengd3d9d662009-07-23 18:27:47 +0000751 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000752}
753
754/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000755/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000756bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000757 MachineInstr *CPEMI, unsigned MaxDisp,
758 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000759 unsigned CPEOffset = GetOffsetOf(CPEMI);
760 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000761
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000762 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 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000769
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000770 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000771}
772
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000773#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +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 Goodwin5e47a9a2009-06-30 18:04:13 +0000783 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
784 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000785 return PredMI->getOperand(0).getMBB() == Succ;
786 return false;
787}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000788#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000789
Bob Wilson84945262009-05-12 17:09:30 +0000790void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000791 int delta) {
792 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000793 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
794 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000795 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000796 // 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 Chengd3d9d662009-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 Cheng4a8ea212009-08-11 07:36:14 +0000804 unsigned OldOffset = BBOffsets[i] - delta;
805 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000806 // add new padding
807 BBSizes[i] += 2;
808 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000809 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000810 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000811 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000812 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000813 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000814 }
Evan Chengd3d9d662009-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 Cheng78947622009-07-24 18:20:44 +0000817 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000818 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000819 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
820 unsigned OldMIOffset = NewMIOffset - delta;
821 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000822 // remove existing padding
823 BBSizes[i] -= 2;
824 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000825 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000826 // add new padding
827 BBSizes[i] += 2;
828 delta += 2;
829 }
830 }
831 if (delta==0)
832 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000833 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000834 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000835 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000836}
837
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000838/// DecrementOldEntry - find the constant pool entry with index CPI
839/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000840/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000841/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000842
Evan Chenged884f32007-04-03 23:39:48 +0000843bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000844 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000845 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
846 assert(CPE && "Unexpected!");
847 if (--CPE->RefCount == 0) {
848 RemoveDeadCPEMI(CPEMI);
849 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000850 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000851 return true;
852 }
853 return false;
854}
855
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000856/// 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 Cheng5d8f1ca2009-07-21 23:56:01 +0000868 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000869 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000870 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000871 }
872
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000873 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000874 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +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 Cheng5d8f1ca2009-07-21 23:56:01 +0000883 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +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 Gohmand735b802008-10-03 15:45:36 +0000889 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000890 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +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.
Evan Chenged884f32007-04-03 23:39:48 +0000897 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898 }
899 }
900 return 0;
901}
902
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000903/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
904/// the specific unconditional branch instruction.
905static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-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 Grosbach764ab522009-08-11 15:33:49 +0000914
David Goodwin5e47a9a2009-06-30 18:04:13 +0000915 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000916}
917
Dale Johannesen8593e412007-04-29 19:19:30 +0000918/// AcceptWater - Small amount of common code factored out of the following.
919
Bob Wilson84945262009-05-12 17:09:30 +0000920MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +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
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000932/// 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
Dale Johannesen8593e412007-04-29 19:19:30 +0000935/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000936/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000937/// water that will not introduce padding to water that will; within each
938/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000939bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000940 MachineBasicBlock** NewMBB) {
941 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
942 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000943 if (!WaterList.empty()) {
944 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000945 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000946 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000947 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000948 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000950 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +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;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000960 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000961 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000962 if (IP == B)
963 break;
964 }
965 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000966 if (isThumb && WaterBBThatWouldPad) {
967 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
968 return true;
969 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000970 return false;
971}
972
Bob Wilson84945262009-05-12 17:09:30 +0000973/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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 Wilson84945262009-05-12 17:09:30 +0000981void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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 Wilson84945262009-05-12 17:09:30 +0000987 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000988 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000989 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000990
991 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000992 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-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
Dale Johannesen8593e412007-04-29 19:19:30 +0000995 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000996 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000997 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000998 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000999 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1000 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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 Goodwin5e47a9a2009-06-30 18:04:13 +00001010 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001011 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1012 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001013 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001014 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001015 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001016 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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 Chengd3d9d662009-07-23 18:27:47 +00001021 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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
Dale Johannesen8593e412007-04-29 19:19:30 +00001027 // 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
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001034 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001035 // island is handled inside OffsetIsInRange.
1036 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001037 // 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 Wilson84945262009-05-12 17:09:30 +00001042 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001043 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001044 unsigned EndInsertOffset = BaseInsertOffset +
1045 CPEMI->getOperand(2).getImm();
1046 MachineBasicBlock::iterator MI = UserMI;
1047 ++MI;
1048 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001049 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001050 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001051 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001052 MI = next(MI)) {
1053 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001054 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001055 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001056 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1057 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1058 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +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
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001071/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001072/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001073/// place in-range. Return true if we changed any addresses (thus must run
1074/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001075bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001076 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001077 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001078 MachineInstr *UserMI = U.MI;
1079 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001080 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001081 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001082 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001083 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001084 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001085 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001086
Dale Johannesen88e37ae2007-02-23 05:02:36 +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 Wilson39bf0512009-05-12 17:35:29 +00001095 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +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).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001100
Dale Johannesen8593e412007-04-29 19:19:30 +00001101 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001102 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001103 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001105 }
1106
1107 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001108 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1109 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +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.
Evan Chenged884f32007-04-03 23:39:48 +00001115 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001116
1117 // Now that we have an island to add the CPE to, clone the original CPE and
1118 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001119 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1120 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001121 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001122 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001123 NumCPEs++;
1124
Dale Johannesen8593e412007-04-29 19:19:30 +00001125 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001126 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001127 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001128 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001129 // Increase the size of the island block to account for the new entry.
1130 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001131 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001132
Evan Chenga8e29892007-01-19 07:51:42 +00001133 // Finally, change the CPI in the instruction operand to be ID.
1134 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001135 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001136 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001137 break;
1138 }
Bob Wilson84945262009-05-12 17:09:30 +00001139
Evan Chengc99ef082007-02-09 20:54:44 +00001140 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001141
Evan Chenga8e29892007-01-19 07:51:42 +00001142 return true;
1143}
1144
Evan Chenged884f32007-04-03 23:39:48 +00001145/// 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();
Dale Johannesen8593e412007-04-29 19:19:30 +00001149 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.
Evan Chenged884f32007-04-03 23:39:48 +00001153 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001154 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001155 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001156 // empty, so fix this.
1157 // All succeeding offsets have the current size value added in, fix this.
1158 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001159 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001160 BBSizes[CPEBB->getNumber()] = 0;
1161 }
Evan Chenged884f32007-04-03 23:39:48 +00001162 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001163 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?
Evan Chenged884f32007-04-03 23:39:48 +00001169}
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 Wilson84945262009-05-12 17:09:30 +00001184 }
Evan Chenged884f32007-04-03 23:39:48 +00001185 return MadeChange;
1186}
1187
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001188/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001189/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001190bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1191 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001192 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001193 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001194 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001195
Evan Chengc99ef082007-02-09 20:54:44 +00001196 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1197 << " from BB#" << MI->getParent()->getNumber()
1198 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001199 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1200 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001201
Dale Johannesen8593e412007-04-29 19:19:30 +00001202 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;
Evan Cheng43aeab62007-01-26 20:38:26 +00001211}
1212
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001213/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1214/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001215bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001216 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001217 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001218
Evan Chengc0dbec72007-01-31 19:57:44 +00001219 // Check to see if the DestBB is already in-range.
1220 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001221 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001222
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001223 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001224 return FixUpUnconditionalBr(MF, Br);
1225 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001226}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001227
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001228/// 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
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001230/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001231/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001232bool
Evan Cheng5657c012009-07-29 02:18:14 +00001233ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001234 MachineInstr *MI = Br.MI;
1235 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001236 if (!isThumb1)
1237 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001238
1239 // Use BL to implement far jump.
1240 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001241 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001242 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001243 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001244 HasFarJump = true;
1245 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001246
Evan Chengc99ef082007-02-09 20:54:44 +00001247 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001248
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001249 return true;
1250}
1251
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001252/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001253/// 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 Cheng5657c012009-07-29 02:18:14 +00001256ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001257 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001258 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001259
Bob Wilson39bf0512009-05-12 17:35:29 +00001260 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001261 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001262 // blt L1
1263 // =>
1264 // bge L2
1265 // b L1
1266 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001267 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001268 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001269 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001270
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();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001275 MachineInstr *BMI = &MBB->back();
1276 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001277
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001278 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001279 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001280 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001281 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001282 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001283 // condition and swap destinations:
1284 // beq L1
1285 // b L2
1286 // =>
1287 // bne L2
1288 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001289 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001290 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001291 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001292 BMI->getOperand(0).setMBB(DestBB);
1293 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001294 MI->getOperand(1).setImm(CC);
1295 return true;
1296 }
1297 }
1298 }
1299
1300 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001301 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001302 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001303 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001304 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001305 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001306 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1307 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001308 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001309 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001310 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001311 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001312
Evan Chengc99ef082007-02-09 20:54:44 +00001313 DOUT << " Insert B to BB#" << DestBB->getNumber()
1314 << " also invert condition and change dest. to BB#"
1315 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001316
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001317 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001318 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001319 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1320 TII->get(MI->getOpcode()))
1321 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001322 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001323 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001324 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001325 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001326 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001327 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001328
1329 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001330 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001331 MI->eraseFromParent();
1332
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001333 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001334 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001335 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001336 return true;
1337}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001338
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001339/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-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.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001342bool ARMConstantIslands::UndoLRSpillRestore() {
1343 bool MadeChange = false;
1344 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1345 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001346 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng48bd7e32009-08-13 06:05:07 +00001347 MI->getOperand(2).getReg() == ARM::PC &&
1348 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001349 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001350 MI->eraseFromParent();
1351 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001352 }
1353 }
1354 return MadeChange;
1355}
Evan Cheng5657c012009-07-29 02:18:14 +00001356
Evan Chenga1efbbd2009-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 Cheng5657c012009-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 Cheng8770f742009-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 Chengd26b14c2009-07-31 18:28:05 +00001438 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001439 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001440 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001441 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-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 Chenga1efbbd2009-08-14 00:32:16 +00001480 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1481 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001482 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001483 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1484 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001485 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001486 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001487
Evan Cheng25f7cfc2009-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 Cheng5657c012009-07-29 02:18:14 +00001513 }
1514 }
1515
1516 return MadeChange;
1517}