blob: d11fafd4cb39fcc7f5f525d370c1d6af4790701c [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"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
54namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000055 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000058 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// special instructions.
60 ///
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000066 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000068 /// by MBB Number. The two-byte pads required for Thumb alignment are
69 /// counted as part of the following block (i.e., the offset and size for
70 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000072
Dale Johannesen99c49a42007-02-25 00:47:03 +000073 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000074 /// The two-byte pads required for Thumb alignment are counted as part of
75 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000076 std::vector<unsigned> BBOffsets;
77
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// WaterList - A sorted list of basic blocks where islands could be placed
79 /// (i.e. blocks that don't fall through to the following block, due
80 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000081 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000082
Bob Wilsonb9239532009-10-15 20:49:47 +000083 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
86
Bob Wilson034de5f2009-10-12 18:52:13 +000087 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
88
Evan Chenga8e29892007-01-19 07:51:42 +000089 /// CPUser - One user of a constant pool, keeping the machine instruction
90 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000091 /// allowed from the instruction to the CP. The HighWaterMark records the
92 /// highest basic block where a new CPEntry can be placed. To ensure this
93 /// pass terminates, the CP entries are initially placed at the end of the
94 /// function and then move monotonically to lower addresses. The
95 /// exception to this rule is when the current CP entry for a particular
96 /// CPUser is out of range, but there is another CP entry for the same
97 /// constant value in range. We want to use the existing in-range CP
98 /// entry, but if it later moves out of range, the search for new water
99 /// should resume where it left off. The HighWaterMark is used to record
100 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000101 struct CPUser {
102 MachineInstr *MI;
103 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000104 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000105 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000106 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000107 bool IsSoImm;
108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
111 HighWaterMark = CPEMI->getParent();
112 }
Evan Chenga8e29892007-01-19 07:51:42 +0000113 };
Bob Wilson84945262009-05-12 17:09:30 +0000114
Evan Chenga8e29892007-01-19 07:51:42 +0000115 /// CPUsers - Keep track of all of the machine instructions that use various
116 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000117 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000118
Evan Chengc99ef082007-02-09 20:54:44 +0000119 /// CPEntry - One per constant pool entry, keeping the machine instruction
120 /// pointer, the constpool index, and the number of CPUser's which
121 /// reference this entry.
122 struct CPEntry {
123 MachineInstr *CPEMI;
124 unsigned CPI;
125 unsigned RefCount;
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
128 };
129
130 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000131 /// instructions. For each original constpool index (i.e. those that
132 /// existed upon entry to this pass), it keeps a vector of entries.
133 /// Original elements are cloned as we go along; the clones are
134 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000135 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000136
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 /// ImmBranch - One per immediate branch, keeping the machine instruction
138 /// pointer, conditional or unconditional, the max displacement,
139 /// and (if isCond is true) the corresponding unconditional branch
140 /// opcode.
141 struct ImmBranch {
142 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000143 unsigned MaxDisp : 31;
144 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000145 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000148 };
149
Evan Cheng2706f972007-05-16 05:14:06 +0000150 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000151 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000152 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000153
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
155 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000156 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000157
Evan Cheng5657c012009-07-29 02:18:14 +0000158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
160
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
163 bool HasFarJump;
164
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000165 /// HasInlineAsm - True if the function contains inline assembly.
166 bool HasInlineAsm;
167
Evan Chenga8e29892007-01-19 07:51:42 +0000168 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000169 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000170 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000171 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000172 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000173 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000174 public:
Devang Patel19974732007-05-03 01:11:54 +0000175 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000176 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000177
Evan Cheng5657c012009-07-29 02:18:14 +0000178 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000179
180 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000181 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000182 }
Bob Wilson84945262009-05-12 17:09:30 +0000183
Evan Chenga8e29892007-01-19 07:51:42 +0000184 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000185 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000186 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000187 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000188 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000189 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000190 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000191 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000192 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000193 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000194 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000195 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000196 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000197 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000198 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000199 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000200 void RemoveDeadCPEMI(MachineInstr *CPEMI);
201 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000202 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000203 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
204 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000205 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000206 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000207 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000208 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000209 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000210 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
211 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
212 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000213 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000214 bool OptimizeThumb2Instructions(MachineFunction &MF);
215 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000216 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000217 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000218 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
219 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000220
Evan Chenga8e29892007-01-19 07:51:42 +0000221 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000222 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000223 void verify(MachineFunction &MF);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000224 void verifySizes(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000225 };
Devang Patel19974732007-05-03 01:11:54 +0000226 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000227}
228
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000229// verifySizes - Recalculate BB sizes from scratch and validate that the result
230// matches the values we've been using.
231void ARMConstantIslands::verifySizes(MachineFunction &MF) {
232 unsigned Offset = 0;
233 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
234 MBBI != E; ++MBBI) {
235 MachineBasicBlock &MBB = *MBBI;
236 unsigned MBBSize = 0;
237 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
238 I != E; ++I) {
239 // Add instruction size to MBBSize.
240 MBBSize += TII->GetInstSizeInBytes(I);
241 }
242 // In thumb mode, if this block is a constpool island, we may need padding
243 // so it's aligned on 4 byte boundary.
244 if (isThumb &&
245 !MBB.empty() &&
246 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
247 ((Offset%4) != 0 || HasInlineAsm))
248 MBBSize += 2;
249 Offset += MBBSize;
250
251 DEBUG(errs() << "block #" << MBB.getNumber() << ": "
252 << MBBSize << " bytes (expecting " << BBSizes[MBB.getNumber()]
253 << (MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY ?
254 " CONSTANTPOOL" : "") << ")\n");
255#ifndef NDEBUG
256 if (MBBSize != BBSizes[MBB.getNumber()])
257 MBB.dump();
258#endif
259 assert (MBBSize == BBSizes[MBB.getNumber()] && "block size mismatch!");
260 }
261}
262
Dale Johannesen8593e412007-04-29 19:19:30 +0000263/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000264void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000265 assert(BBOffsets.size() == BBSizes.size());
266 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
267 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000268 if (!isThumb)
269 return;
270#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000271 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000272 MBBI != E; ++MBBI) {
273 MachineBasicBlock *MBB = MBBI;
274 if (!MBB->empty() &&
275 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
276 unsigned MBBId = MBB->getNumber();
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000277 assert(HasInlineAsm ||
278 (BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000279 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000280 }
281 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000282#endif
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000283 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
284 CPUser &U = CPUsers[i];
285 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
286 assert (CPEIsInRange(U.MI, UserOffset, U.CPEMI, U.MaxDisp, U.NegOk, true));
287 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000288}
289
290/// print block size and offset information - debugging
291void ARMConstantIslands::dumpBBs() {
292 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000293 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
294 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000295 }
296}
297
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000298/// createARMConstantIslandPass - returns an instance of the constpool
299/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000300FunctionPass *llvm::createARMConstantIslandPass() {
301 return new ARMConstantIslands();
302}
303
Evan Cheng5657c012009-07-29 02:18:14 +0000304bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
305 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000306
Evan Cheng5657c012009-07-29 02:18:14 +0000307 TII = MF.getTarget().getInstrInfo();
308 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000309 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
310
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000311 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000312 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000313 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000314
315 HasFarJump = false;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000316 HasInlineAsm = false;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000317
Evan Chenga8e29892007-01-19 07:51:42 +0000318 // Renumber all of the machine basic blocks in the function, guaranteeing that
319 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000320 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000321
Jim Grosbach80697d12009-11-12 17:25:07 +0000322 // Try to reorder and otherwise adjust the block layout to make good use
323 // of the TB[BH] instructions.
324 bool MadeChange = false;
325 if (isThumb2 && AdjustJumpTableBlocks) {
326 JumpTableFunctionScan(MF);
327 MadeChange |= ReorderThumb2JumpTables(MF);
328 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000329 T2JumpTables.clear();
330 // Blocks may have shifted around. Keep the numbering up to date.
331 MF.RenumberBlocks();
332 }
333
Evan Chengd26b14c2009-07-31 18:28:05 +0000334 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000335 // This is so we can keep exact track of where the alignment padding goes.
336
Evan Chengd26b14c2009-07-31 18:28:05 +0000337 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000338 // aligned.
339 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000340
Evan Chenga8e29892007-01-19 07:51:42 +0000341 // Perform the initial placement of the constant pool entries. To start with,
342 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000343 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000344 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000345 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000346 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000347 AFI->setAlign(2U);
348 }
Bob Wilson84945262009-05-12 17:09:30 +0000349
Evan Chenga8e29892007-01-19 07:51:42 +0000350 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000351 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000352
Evan Chenga8e29892007-01-19 07:51:42 +0000353 // Do the initial scan of the function, building up information about the
354 // sizes of each block, the location of all the water, and finding all of the
355 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000356 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000357 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000358
Evan Chenged884f32007-04-03 23:39:48 +0000359 /// Remove dead constant pool entries.
360 RemoveUnusedCPEntries();
361
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000362 // Iteratively place constant pool entries and fix up branches until there
363 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000364 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000365 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000366 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000367 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000368 CPChange |= HandleConstantPoolUser(MF, i);
369 if (CPChange && ++NoCPIters > 30)
370 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000371 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000372
373 // Clear NewWaterList now. If we split a block for branches, it should
374 // appear as "new water" for the next iteration of constant pool placement.
375 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000376
377 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000378 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000379 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
380 if (BRChange && ++NoBRIters > 30)
381 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000382 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000383
384 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000385 break;
386 MadeChange = true;
387 }
Evan Chenged884f32007-04-03 23:39:48 +0000388
Evan Chenga1efbbd2009-08-14 00:32:16 +0000389 // Shrink 32-bit Thumb2 branch, load, and store instructions.
390 if (isThumb2)
391 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000392
Dale Johannesen8593e412007-04-29 19:19:30 +0000393 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000394 verify(MF);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000395 verifySizes(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000396
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000397 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
398 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000399 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000400 MadeChange |= UndoLRSpillRestore();
401
Evan Chenga8e29892007-01-19 07:51:42 +0000402 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000403 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000404 WaterList.clear();
405 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000406 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000407 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000408 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000409 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000410
411 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000412}
413
414/// DoInitialPlacement - Perform the initial placement of the constant pool
415/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000416void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000417 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000418 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000419 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
420 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000421
Evan Chenga8e29892007-01-19 07:51:42 +0000422 // Add all of the constants from the constant pool to the end block, use an
423 // identity mapping of CPI's to CPE's.
424 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000425 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000426
Evan Cheng5657c012009-07-29 02:18:14 +0000427 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000428 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000429 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000430 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
431 // we would have to pad them out or something so that instructions stay
432 // aligned.
433 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
434 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000435 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000436 .addImm(i).addConstantPoolIndex(i).addImm(Size);
437 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000438
439 // Add a new CPEntry, but no corresponding CPUser yet.
440 std::vector<CPEntry> CPEs;
441 CPEs.push_back(CPEntry(CPEMI, i));
442 CPEntries.push_back(CPEs);
443 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000444 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
445 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000446 }
447}
448
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000449/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000450/// into the block immediately after it.
451static bool BBHasFallthrough(MachineBasicBlock *MBB) {
452 // Get the next machine basic block in the function.
453 MachineFunction::iterator MBBI = MBB;
454 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
455 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000456
Evan Chenga8e29892007-01-19 07:51:42 +0000457 MachineBasicBlock *NextBB = next(MBBI);
458 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
459 E = MBB->succ_end(); I != E; ++I)
460 if (*I == NextBB)
461 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000462
Evan Chenga8e29892007-01-19 07:51:42 +0000463 return false;
464}
465
Evan Chengc99ef082007-02-09 20:54:44 +0000466/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
467/// look up the corresponding CPEntry.
468ARMConstantIslands::CPEntry
469*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
470 const MachineInstr *CPEMI) {
471 std::vector<CPEntry> &CPEs = CPEntries[CPI];
472 // Number of entries per constpool index should be small, just do a
473 // linear search.
474 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
475 if (CPEs[i].CPEMI == CPEMI)
476 return &CPEs[i];
477 }
478 return NULL;
479}
480
Jim Grosbach80697d12009-11-12 17:25:07 +0000481/// JumpTableFunctionScan - Do a scan of the function, building up
482/// information about the sizes of each block and the locations of all
483/// the jump tables.
484void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000485 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
486 MBBI != E; ++MBBI) {
487 MachineBasicBlock &MBB = *MBBI;
488
Jim Grosbach80697d12009-11-12 17:25:07 +0000489 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000490 I != E; ++I)
491 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
492 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000493 }
494}
495
Evan Chenga8e29892007-01-19 07:51:42 +0000496/// InitialFunctionScan - Do the initial scan of the function, building up
497/// information about the sizes of each block, the location of all the water,
498/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000499void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000500 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000501 // First thing, see if the function has any inline assembly in it. If so,
502 // we have to be conservative about alignment assumptions, as we don't
503 // know for sure the size of any instructions in the inline assembly.
504 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
505 MBBI != E; ++MBBI) {
506 MachineBasicBlock &MBB = *MBBI;
507 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
508 I != E; ++I)
509 if (I->getOpcode() == ARM::INLINEASM)
510 HasInlineAsm = true;
511 }
512
513 // Now go back through the instructions and build up our data structures
Dale Johannesen99c49a42007-02-25 00:47:03 +0000514 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000515 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000516 MBBI != E; ++MBBI) {
517 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000518
Evan Chenga8e29892007-01-19 07:51:42 +0000519 // If this block doesn't fall through into the next MBB, then this is
520 // 'water' that a constant pool island could be placed.
521 if (!BBHasFallthrough(&MBB))
522 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000523
Evan Chenga8e29892007-01-19 07:51:42 +0000524 unsigned MBBSize = 0;
525 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
526 I != E; ++I) {
527 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000528 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000529
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000530 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000531 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000532 bool isCond = false;
533 unsigned Bits = 0;
534 unsigned Scale = 1;
535 int UOpc = Opc;
536 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000537 default:
538 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000539 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000540 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000541 // be right, functions containing these must be 4-byte aligned.
542 AFI->setAlign(2U);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000543 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
Evan Cheng5657c012009-07-29 02:18:14 +0000544 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000545 MBBSize += 2; // padding
546 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000547 case ARM::t2BR_JT:
548 T2JumpTables.push_back(I);
549 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000550 case ARM::Bcc:
551 isCond = true;
552 UOpc = ARM::B;
553 // Fallthrough
554 case ARM::B:
555 Bits = 24;
556 Scale = 4;
557 break;
558 case ARM::tBcc:
559 isCond = true;
560 UOpc = ARM::tB;
561 Bits = 8;
562 Scale = 2;
563 break;
564 case ARM::tB:
565 Bits = 11;
566 Scale = 2;
567 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000568 case ARM::t2Bcc:
569 isCond = true;
570 UOpc = ARM::t2B;
571 Bits = 20;
572 Scale = 2;
573 break;
574 case ARM::t2B:
575 Bits = 24;
576 Scale = 2;
577 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000578 }
Evan Chengb43216e2007-02-01 10:16:15 +0000579
580 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000581 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000582 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000583 }
584
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000585 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
586 PushPopMIs.push_back(I);
587
Evan Chengd3d9d662009-07-23 18:27:47 +0000588 if (Opc == ARM::CONSTPOOL_ENTRY)
589 continue;
590
Evan Chenga8e29892007-01-19 07:51:42 +0000591 // Scan the instructions for constant pool operands.
592 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000593 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000594 // We found one. The addressing mode tells us the max displacement
595 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000596
Evan Chenga8e29892007-01-19 07:51:42 +0000597 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000598 unsigned Bits = 0;
599 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000600 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000601 bool IsSoImm = false;
602
603 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000604 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000605 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000606 break;
607
608 // Taking the address of a CP entry.
609 case ARM::LEApcrel:
610 // This takes a SoImm, which is 8 bit immediate rotated. We'll
611 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000612 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000613 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000614 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000615 Scale = 4;
616 NegOk = true;
617 IsSoImm = true;
618 break;
619 case ARM::t2LEApcrel:
620 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000621 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000622 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000623 case ARM::tLEApcrel:
624 Bits = 8;
625 Scale = 4;
626 break;
627
628 case ARM::LDR:
629 case ARM::LDRcp:
630 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000631 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000632 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000633 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000634
635 case ARM::tLDRpci:
636 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000637 Bits = 8;
638 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000639 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000640
Jim Grosbache5165492009-11-09 00:11:35 +0000641 case ARM::VLDRD:
642 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000643 Bits = 8;
644 Scale = 4; // +-(offset_8*4)
645 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000646 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000647 }
Evan Chengb43216e2007-02-01 10:16:15 +0000648
Evan Chenga8e29892007-01-19 07:51:42 +0000649 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000650 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000651 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000652 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000653 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000654
655 // Increment corresponding CPEntry reference count.
656 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
657 assert(CPE && "Cannot find a corresponding CPEntry!");
658 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000659
Evan Chenga8e29892007-01-19 07:51:42 +0000660 // Instructions can only use one CP entry, don't bother scanning the
661 // rest of the operands.
662 break;
663 }
664 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000665
Dale Johannesen8593e412007-04-29 19:19:30 +0000666 // In thumb mode, if this block is a constpool island, we may need padding
667 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000668 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000669 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000670 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000671 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000672 MBBSize += 2;
673
Evan Chenga8e29892007-01-19 07:51:42 +0000674 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000675 BBOffsets.push_back(Offset);
676 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000677 }
678}
679
Evan Chenga8e29892007-01-19 07:51:42 +0000680/// GetOffsetOf - Return the current offset of the specified machine instruction
681/// from the start of the function. This offset changes as stuff is moved
682/// around inside the function.
683unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
684 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000685
Evan Chenga8e29892007-01-19 07:51:42 +0000686 // The offset is composed of two things: the sum of the sizes of all MBB's
687 // before this instruction's block, and the offset from the start of the block
688 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000689 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000690
Dale Johannesen8593e412007-04-29 19:19:30 +0000691 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
692 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000693 if (isThumb &&
694 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000695 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000696 Offset += 2;
697
Evan Chenga8e29892007-01-19 07:51:42 +0000698 // Sum instructions before MI in MBB.
699 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
700 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
701 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000702 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000703 }
704}
705
706/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
707/// ID.
708static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
709 const MachineBasicBlock *RHS) {
710 return LHS->getNumber() < RHS->getNumber();
711}
712
713/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
714/// machine function, it upsets all of the block numbers. Renumber the blocks
715/// and update the arrays that parallel this numbering.
716void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
717 // Renumber the MBB's to keep them consequtive.
718 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000719
Evan Chenga8e29892007-01-19 07:51:42 +0000720 // Insert a size into BBSizes to align it properly with the (newly
721 // renumbered) block numbers.
722 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000723
724 // Likewise for BBOffsets.
725 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000726
727 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000728 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000729 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000730 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
731 CompareMBBNumbers);
732 WaterList.insert(IP, NewBB);
733}
734
735
736/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000737/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000738/// account for this change and returns the newly created block.
739MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000740 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000741 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000742
743 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000744 MachineBasicBlock *NewBB =
745 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000746 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000747 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000748
Evan Chenga8e29892007-01-19 07:51:42 +0000749 // Splice the instructions starting with MI over to NewBB.
750 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000751
Evan Chenga8e29892007-01-19 07:51:42 +0000752 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000753 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000754 // There doesn't seem to be meaningful DebugInfo available; this doesn't
755 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000756 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
757 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000758 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000759
Evan Chenga8e29892007-01-19 07:51:42 +0000760 // Update the CFG. All succs of OrigBB are now succs of NewBB.
761 while (!OrigBB->succ_empty()) {
762 MachineBasicBlock *Succ = *OrigBB->succ_begin();
763 OrigBB->removeSuccessor(Succ);
764 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000765
Evan Chenga8e29892007-01-19 07:51:42 +0000766 // This pass should be run after register allocation, so there should be no
767 // PHI nodes to update.
768 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
769 && "PHI nodes should be eliminated by now!");
770 }
Bob Wilson84945262009-05-12 17:09:30 +0000771
Evan Chenga8e29892007-01-19 07:51:42 +0000772 // OrigBB branches to NewBB.
773 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000774
Evan Chenga8e29892007-01-19 07:51:42 +0000775 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000776 // This is almost the same as UpdateForInsertedWaterBlock, except that
777 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000778 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000779
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000780 // Insert a size into BBSizes to align it properly with the (newly
781 // renumbered) block numbers.
782 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000783
Dale Johannesen99c49a42007-02-25 00:47:03 +0000784 // Likewise for BBOffsets.
785 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
786
Bob Wilson84945262009-05-12 17:09:30 +0000787 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000788 // available water after it (but not if it's already there, which happens
789 // when splitting before a conditional branch that is followed by an
790 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000791 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000792 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
793 CompareMBBNumbers);
794 MachineBasicBlock* WaterBB = *IP;
795 if (WaterBB == OrigBB)
796 WaterList.insert(next(IP), NewBB);
797 else
798 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000799 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000800
Dale Johannesen8593e412007-04-29 19:19:30 +0000801 // Figure out how large the first NewMBB is. (It cannot
802 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000803 unsigned NewBBSize = 0;
804 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
805 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000806 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000807
Dale Johannesen99c49a42007-02-25 00:47:03 +0000808 unsigned OrigBBI = OrigBB->getNumber();
809 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000810 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000811 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000812
Evan Chenga8e29892007-01-19 07:51:42 +0000813 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000814 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000815 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000816 BBSizes[OrigBBI] -= NewBBSize - delta;
817
818 // ...and adjust BBOffsets for NewBB accordingly.
819 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
820
821 // All BBOffsets following these blocks must be modified.
822 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000823
824 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000825}
826
Dale Johannesen8593e412007-04-29 19:19:30 +0000827/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000828/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000829/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000830bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000831 unsigned TrialOffset, unsigned MaxDisp,
832 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000833 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
834 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000835 // Effectively, the valid range of displacements is 2 bytes smaller for such
836 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000837 unsigned TotalAdj = 0;
838 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000839 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000840 TotalAdj = 2;
841 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000842 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000843 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000844 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000845 TotalAdj += 2;
846 }
847
848 // In Thumb2 mode, later branch adjustments can shift instructions up and
849 // cause alignment change. In the worst case scenario this can cause the
850 // user's effective address to be subtracted by 2 and the CPE's address to
851 // be plus 2.
852 if (isThumb2 && TotalAdj != 4)
853 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000854
Dale Johannesen99c49a42007-02-25 00:47:03 +0000855 if (UserOffset <= TrialOffset) {
856 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000857 if (TrialOffset - UserOffset <= MaxDisp)
858 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000859 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000860 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000861 if (UserOffset - TrialOffset <= MaxDisp)
862 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000863 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000864 }
865 return false;
866}
867
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000868/// WaterIsInRange - Returns true if a CPE placed after the specified
869/// Water (a basic block) will be in range for the specific MI.
870
871bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000872 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000873 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000874 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000875 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000876
Dale Johannesend959aa42007-04-02 20:31:06 +0000877 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000878 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000879 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000880 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000881
Evan Chengd3d9d662009-07-23 18:27:47 +0000882 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883}
884
885/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000886/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000887bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000888 MachineInstr *CPEMI, unsigned MaxDisp,
889 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000890 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000891 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000892
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000893 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000894 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
895 << " max delta=" << MaxDisp
896 << " insn address=" << UserOffset
897 << " CPE address=" << CPEOffset
898 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000899 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000900
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000901 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000902}
903
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000904#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000905/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
906/// unconditionally branches to its only successor.
907static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
908 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
909 return false;
910
911 MachineBasicBlock *Succ = *MBB->succ_begin();
912 MachineBasicBlock *Pred = *MBB->pred_begin();
913 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000914 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
915 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000916 return PredMI->getOperand(0).getMBB() == Succ;
917 return false;
918}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000919#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000920
Bob Wilson84945262009-05-12 17:09:30 +0000921void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000922 int delta) {
923 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000924 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
925 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000926 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000927 // If some existing blocks have padding, adjust the padding as needed, a
928 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000929 if (!isThumb)
930 continue;
931 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000932 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000933 // Constant pool entries require padding.
934 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000935 unsigned OldOffset = BBOffsets[i] - delta;
936 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000937 // add new padding
938 BBSizes[i] += 2;
939 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000940 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000941 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000942 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000943 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000944 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000945 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000946 // Thumb1 jump tables require padding. They should be at the end;
947 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000948 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000949 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000950 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
951 unsigned OldMIOffset = NewMIOffset - delta;
952 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000953 // remove existing padding
954 BBSizes[i] -= 2;
955 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000956 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000957 // add new padding
958 BBSizes[i] += 2;
959 delta += 2;
960 }
961 }
962 if (delta==0)
963 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000964 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000965 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000966 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000967}
968
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000969/// DecrementOldEntry - find the constant pool entry with index CPI
970/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000971/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000972/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000973
Evan Chenged884f32007-04-03 23:39:48 +0000974bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000975 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000976 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
977 assert(CPE && "Unexpected!");
978 if (--CPE->RefCount == 0) {
979 RemoveDeadCPEMI(CPEMI);
980 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000981 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000982 return true;
983 }
984 return false;
985}
986
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000987/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
988/// if not, see if an in-range clone of the CPE is in range, and if so,
989/// change the data structures so the user references the clone. Returns:
990/// 0 = no existing entry found
991/// 1 = entry found, and there were no code insertions or deletions
992/// 2 = entry found, and there were code insertions or deletions
993int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
994{
995 MachineInstr *UserMI = U.MI;
996 MachineInstr *CPEMI = U.CPEMI;
997
998 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000999 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001000 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001001 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001002 }
1003
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001004 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001005 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001006 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1007 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1008 // We already tried this one
1009 if (CPEs[i].CPEMI == CPEMI)
1010 continue;
1011 // Removing CPEs can leave empty entries, skip
1012 if (CPEs[i].CPEMI == NULL)
1013 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001014 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001015 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1016 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001017 // Point the CPUser node to the replacement
1018 U.CPEMI = CPEs[i].CPEMI;
1019 // Change the CPI in the instruction operand to refer to the clone.
1020 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001021 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001022 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001023 break;
1024 }
1025 // Adjust the refcount of the clone...
1026 CPEs[i].RefCount++;
1027 // ...and the original. If we didn't remove the old entry, none of the
1028 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001029 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001030 }
1031 }
1032 return 0;
1033}
1034
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001035/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1036/// the specific unconditional branch instruction.
1037static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001038 switch (Opc) {
1039 case ARM::tB:
1040 return ((1<<10)-1)*2;
1041 case ARM::t2B:
1042 return ((1<<23)-1)*2;
1043 default:
1044 break;
1045 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001046
David Goodwin5e47a9a2009-06-30 18:04:13 +00001047 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001048}
1049
Bob Wilsonb9239532009-10-15 20:49:47 +00001050/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001051/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001052/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001053/// is set to the WaterList entry. For Thumb, prefer water that will not
1054/// introduce padding to water that will. To ensure that this pass
1055/// terminates, the CPE location for a particular CPUser is only allowed to
1056/// move to a lower address, so search backward from the end of the list and
1057/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001058bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001059 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001060 if (WaterList.empty())
1061 return false;
1062
Bob Wilson32c50e82009-10-12 20:45:53 +00001063 bool FoundWaterThatWouldPad = false;
1064 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001065 for (water_iterator IP = prior(WaterList.end()),
1066 B = WaterList.begin();; --IP) {
1067 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001068 // Check if water is in range and is either at a lower address than the
1069 // current "high water mark" or a new water block that was created since
1070 // the previous iteration by inserting an unconditional branch. In the
1071 // latter case, we want to allow resetting the high water mark back to
1072 // this new water since we haven't seen it before. Inserting branches
1073 // should be relatively uncommon and when it does happen, we want to be
1074 // sure to take advantage of it for all the CPEs near that block, so that
1075 // we don't insert more branches than necessary.
1076 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1077 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1078 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001079 unsigned WBBId = WaterBB->getNumber();
1080 if (isThumb &&
1081 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1082 // This is valid Water, but would introduce padding. Remember
1083 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001084 if (!FoundWaterThatWouldPad) {
1085 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001086 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001087 }
Bob Wilson3b757352009-10-12 19:04:03 +00001088 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001089 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001090 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001091 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001092 }
Bob Wilson3b757352009-10-12 19:04:03 +00001093 if (IP == B)
1094 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001095 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001096 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001097 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001098 return true;
1099 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001100 return false;
1101}
1102
Bob Wilson84945262009-05-12 17:09:30 +00001103/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1105/// block is used if in range, and the conditional branch munged so control
1106/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001107/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001108/// block following which the new island can be inserted (the WaterList
1109/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001110void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001111 unsigned UserOffset,
1112 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001113 CPUser &U = CPUsers[CPUserIndex];
1114 MachineInstr *UserMI = U.MI;
1115 MachineInstr *CPEMI = U.CPEMI;
1116 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001117 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001118 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001119 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001120
Bob Wilson36fa5322009-10-15 05:10:36 +00001121 // If the block does not end in an unconditional branch already, and if the
1122 // end of the block is within range, make new water there. (The addition
1123 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1124 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001125 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001126 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001127 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1128 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001129 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001130 if (&UserMBB->back() == UserMI)
1131 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001132 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001133 // Add an unconditional branch from UserMBB to fallthrough block.
1134 // Record it for branch lengthening; this new branch will not get out of
1135 // range, but if the preceding conditional branch is out of range, the
1136 // targets will be exchanged, and the altered branch may be out of
1137 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001138 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001139 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001140 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001141 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001142 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001143 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001144 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001145 BBSizes[UserMBB->getNumber()] += delta;
1146 AdjustBBOffsetsAfter(UserMBB, delta);
1147 } else {
1148 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001149 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001150 // and constant pool entries are 4 bytes: if instruction I references
1151 // island CPE, and instruction I+1 references CPE', it will
1152 // not work well to put CPE as far forward as possible, since then
1153 // CPE' cannot immediately follow it (that location is 2 bytes
1154 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001155 // a new island. So, we make a first guess, then walk through the
1156 // instructions between the one currently being looked at and the
1157 // possible insertion point, and make sure any other instructions
1158 // that reference CPEs will be able to use the same island area;
1159 // if not, we back up the insertion point.
1160
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001161 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001162 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001163 // island is handled inside OffsetIsInRange.
1164 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001165 // This could point off the end of the block if we've already got
1166 // constant pool entries following this block; only the last one is
1167 // in the water list. Back past any possible branches (allow for a
1168 // conditional and a maximally long unconditional).
1169 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001170 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001171 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172 unsigned EndInsertOffset = BaseInsertOffset +
1173 CPEMI->getOperand(2).getImm();
1174 MachineBasicBlock::iterator MI = UserMI;
1175 ++MI;
1176 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001177 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001178 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001179 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001180 MI = next(MI)) {
1181 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001182 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001183 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001184 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1185 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1186 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001187 }
1188 // This is overly conservative, as we don't account for CPEMIs
1189 // being reused within the block, but it doesn't matter much.
1190 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1191 CPUIndex++;
1192 }
1193 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001194 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001195 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001196 }
1197}
1198
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001199/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001200/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001201/// place in-range. Return true if we changed any addresses (thus must run
1202/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001203bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001204 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001205 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001206 MachineInstr *UserMI = U.MI;
1207 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001208 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001209 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001210 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001211 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001212 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001213
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001214 // See if the current entry is within range, or there is a clone of it
1215 // in range.
1216 int result = LookForExistingCPEntry(U, UserOffset);
1217 if (result==1) return false;
1218 else if (result==2) return true;
1219
1220 // No existing clone of this CPE is within range.
1221 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001222 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223
Bob Wilsonf98032e2009-10-12 21:23:15 +00001224 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001225 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1226 MachineBasicBlock *NewMBB;
1227 water_iterator IP;
1228 if (LookForWater(U, UserOffset, IP)) {
1229 DEBUG(errs() << "found water in range\n");
1230 MachineBasicBlock *WaterBB = *IP;
1231
1232 // If the original WaterList entry was "new water" on this iteration,
1233 // propagate that to the new island. This is just keeping NewWaterList
1234 // updated to match the WaterList, which will be updated below.
1235 if (NewWaterList.count(WaterBB)) {
1236 NewWaterList.erase(WaterBB);
1237 NewWaterList.insert(NewIsland);
1238 }
1239 // The new CPE goes before the following block (NewMBB).
1240 NewMBB = next(MachineFunction::iterator(WaterBB));
1241
1242 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001243 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001244 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001245 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001246
1247 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1248 // called while handling branches so that the water will be seen on the
1249 // next iteration for constant pools, but in this context, we don't want
1250 // it. Check for this so it will be removed from the WaterList.
1251 // Also remove any entry from NewWaterList.
1252 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1253 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1254 if (IP != WaterList.end())
1255 NewWaterList.erase(WaterBB);
1256
1257 // We are adding new water. Update NewWaterList.
1258 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001259 }
1260
Bob Wilsonb9239532009-10-15 20:49:47 +00001261 // Remove the original WaterList entry; we want subsequent insertions in
1262 // this vicinity to go after the one we're about to insert. This
1263 // considerably reduces the number of times we have to move the same CPE
1264 // more than once and is also important to ensure the algorithm terminates.
1265 if (IP != WaterList.end())
1266 WaterList.erase(IP);
1267
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001268 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001269 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001270
1271 // Update internal data structures to account for the newly inserted MBB.
1272 UpdateForInsertedWaterBlock(NewIsland);
1273
1274 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001275 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001276
1277 // Now that we have an island to add the CPE to, clone the original CPE and
1278 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001279 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001280 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1281 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001282 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001283 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001284 NumCPEs++;
1285
Dale Johannesen8593e412007-04-29 19:19:30 +00001286 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001287 // Compensate for .align 2 in thumb mode.
Jim Grosbach4d8e90a2009-11-19 23:10:28 +00001288 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001289 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001290 // Increase the size of the island block to account for the new entry.
1291 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001292 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001293
Evan Chenga8e29892007-01-19 07:51:42 +00001294 // Finally, change the CPI in the instruction operand to be ID.
1295 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001296 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001297 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001298 break;
1299 }
Bob Wilson84945262009-05-12 17:09:30 +00001300
Chris Lattner705e07f2009-08-23 03:41:05 +00001301 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1302 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001303
Evan Chenga8e29892007-01-19 07:51:42 +00001304 return true;
1305}
1306
Evan Chenged884f32007-04-03 23:39:48 +00001307/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1308/// sizes and offsets of impacted basic blocks.
1309void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1310 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001311 unsigned Size = CPEMI->getOperand(2).getImm();
1312 CPEMI->eraseFromParent();
1313 BBSizes[CPEBB->getNumber()] -= Size;
1314 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001315 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001316 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001317 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001318 // empty, so fix this.
1319 // All succeeding offsets have the current size value added in, fix this.
1320 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001321 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001322 BBSizes[CPEBB->getNumber()] = 0;
1323 }
Evan Chenged884f32007-04-03 23:39:48 +00001324 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001325 AdjustBBOffsetsAfter(CPEBB, -Size);
1326 // An island has only one predecessor BB and one successor BB. Check if
1327 // this BB's predecessor jumps directly to this BB's successor. This
1328 // shouldn't happen currently.
1329 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1330 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001331}
1332
1333/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1334/// are zero.
1335bool ARMConstantIslands::RemoveUnusedCPEntries() {
1336 unsigned MadeChange = false;
1337 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1338 std::vector<CPEntry> &CPEs = CPEntries[i];
1339 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1340 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1341 RemoveDeadCPEMI(CPEs[j].CPEMI);
1342 CPEs[j].CPEMI = NULL;
1343 MadeChange = true;
1344 }
1345 }
Bob Wilson84945262009-05-12 17:09:30 +00001346 }
Evan Chenged884f32007-04-03 23:39:48 +00001347 return MadeChange;
1348}
1349
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001350/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001351/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001352bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1353 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001354 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001355 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001356 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001357
Chris Lattner705e07f2009-08-23 03:41:05 +00001358 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1359 << " from BB#" << MI->getParent()->getNumber()
1360 << " max delta=" << MaxDisp
1361 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1362 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001363
Dale Johannesen8593e412007-04-29 19:19:30 +00001364 if (BrOffset <= DestOffset) {
1365 // Branch before the Dest.
1366 if (DestOffset-BrOffset <= MaxDisp)
1367 return true;
1368 } else {
1369 if (BrOffset-DestOffset <= MaxDisp)
1370 return true;
1371 }
1372 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001373}
1374
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001375/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1376/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001377bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001378 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001379 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001380
Evan Chengc0dbec72007-01-31 19:57:44 +00001381 // Check to see if the DestBB is already in-range.
1382 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001383 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001384
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001385 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001386 return FixUpUnconditionalBr(MF, Br);
1387 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001388}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001389
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001390/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1391/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001392/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001393/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001394bool
Evan Cheng5657c012009-07-29 02:18:14 +00001395ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001396 MachineInstr *MI = Br.MI;
1397 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001398 if (!isThumb1)
1399 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001400
1401 // Use BL to implement far jump.
1402 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001403 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001404 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001405 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001406 HasFarJump = true;
1407 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001408
Chris Lattner705e07f2009-08-23 03:41:05 +00001409 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001410
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001411 return true;
1412}
1413
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001414/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001415/// far away to fit in its displacement field. It is converted to an inverse
1416/// conditional branch + an unconditional branch to the destination.
1417bool
Evan Cheng5657c012009-07-29 02:18:14 +00001418ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001419 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001420 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001421
Bob Wilson39bf0512009-05-12 17:35:29 +00001422 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001423 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001424 // blt L1
1425 // =>
1426 // bge L2
1427 // b L1
1428 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001429 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001430 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001431 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001432
1433 // If the branch is at the end of its MBB and that has a fall-through block,
1434 // direct the updated conditional branch to the fall-through block. Otherwise,
1435 // split the MBB before the next instruction.
1436 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001437 MachineInstr *BMI = &MBB->back();
1438 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001439
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001440 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001441 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001442 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001443 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001444 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001445 // condition and swap destinations:
1446 // beq L1
1447 // b L2
1448 // =>
1449 // bne L2
1450 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001451 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001452 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001453 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1454 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001455 BMI->getOperand(0).setMBB(DestBB);
1456 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001457 MI->getOperand(1).setImm(CC);
1458 return true;
1459 }
1460 }
1461 }
1462
1463 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001464 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001465 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001466 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001467 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001468 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001469 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1470 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001471 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001472 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001473 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001474 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001475
Chris Lattner893e1c92009-08-23 06:49:22 +00001476 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1477 << " also invert condition and change dest. to BB#"
1478 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001479
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001480 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001481 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001482 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1483 TII->get(MI->getOpcode()))
1484 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001485 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001486 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001487 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001488 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001489 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001490 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001491
1492 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001493 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001494 MI->eraseFromParent();
1495
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001496 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001497 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001498 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001499 return true;
1500}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001501
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001502/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001503/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1504/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001505bool ARMConstantIslands::UndoLRSpillRestore() {
1506 bool MadeChange = false;
1507 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1508 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001509 // First two operands are predicates, the third is a zero since there
1510 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001511 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001512 MI->getOperand(3).getReg() == ARM::PC &&
1513 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001514 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001515 MI->eraseFromParent();
1516 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001517 }
1518 }
1519 return MadeChange;
1520}
Evan Cheng5657c012009-07-29 02:18:14 +00001521
Evan Chenga1efbbd2009-08-14 00:32:16 +00001522bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1523 bool MadeChange = false;
1524
1525 // Shrink ADR and LDR from constantpool.
1526 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1527 CPUser &U = CPUsers[i];
1528 unsigned Opcode = U.MI->getOpcode();
1529 unsigned NewOpc = 0;
1530 unsigned Scale = 1;
1531 unsigned Bits = 0;
1532 switch (Opcode) {
1533 default: break;
1534 case ARM::t2LEApcrel:
1535 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1536 NewOpc = ARM::tLEApcrel;
1537 Bits = 8;
1538 Scale = 4;
1539 }
1540 break;
1541 case ARM::t2LDRpci:
1542 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1543 NewOpc = ARM::tLDRpci;
1544 Bits = 8;
1545 Scale = 4;
1546 }
1547 break;
1548 }
1549
1550 if (!NewOpc)
1551 continue;
1552
1553 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1554 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1555 // FIXME: Check if offset is multiple of scale if scale is not 4.
1556 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1557 U.MI->setDesc(TII->get(NewOpc));
1558 MachineBasicBlock *MBB = U.MI->getParent();
1559 BBSizes[MBB->getNumber()] -= 2;
1560 AdjustBBOffsetsAfter(MBB, -2);
1561 ++NumT2CPShrunk;
1562 MadeChange = true;
1563 }
1564 }
1565
Evan Chenga1efbbd2009-08-14 00:32:16 +00001566 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001567 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001568 return MadeChange;
1569}
1570
1571bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001572 bool MadeChange = false;
1573
1574 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1575 ImmBranch &Br = ImmBranches[i];
1576 unsigned Opcode = Br.MI->getOpcode();
1577 unsigned NewOpc = 0;
1578 unsigned Scale = 1;
1579 unsigned Bits = 0;
1580 switch (Opcode) {
1581 default: break;
1582 case ARM::t2B:
1583 NewOpc = ARM::tB;
1584 Bits = 11;
1585 Scale = 2;
1586 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001587 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001588 NewOpc = ARM::tBcc;
1589 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001590 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001591 break;
1592 }
Evan Chengde17fb62009-10-31 23:46:45 +00001593 }
1594 if (NewOpc) {
1595 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1596 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1597 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1598 Br.MI->setDesc(TII->get(NewOpc));
1599 MachineBasicBlock *MBB = Br.MI->getParent();
1600 BBSizes[MBB->getNumber()] -= 2;
1601 AdjustBBOffsetsAfter(MBB, -2);
1602 ++NumT2BrShrunk;
1603 MadeChange = true;
1604 }
1605 }
1606
1607 Opcode = Br.MI->getOpcode();
1608 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001609 continue;
1610
Evan Chengde17fb62009-10-31 23:46:45 +00001611 NewOpc = 0;
1612 unsigned PredReg = 0;
1613 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1614 if (Pred == ARMCC::EQ)
1615 NewOpc = ARM::tCBZ;
1616 else if (Pred == ARMCC::NE)
1617 NewOpc = ARM::tCBNZ;
1618 if (!NewOpc)
1619 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001620 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001621 // Check if the distance is within 126. Subtract starting offset by 2
1622 // because the cmp will be eliminated.
1623 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1624 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1625 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1626 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1627 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1628 unsigned Reg = CmpMI->getOperand(0).getReg();
1629 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1630 if (Pred == ARMCC::AL &&
1631 CmpMI->getOperand(1).getImm() == 0 &&
1632 isARMLowRegister(Reg)) {
1633 MachineBasicBlock *MBB = Br.MI->getParent();
1634 MachineInstr *NewBR =
1635 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1636 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1637 CmpMI->eraseFromParent();
1638 Br.MI->eraseFromParent();
1639 Br.MI = NewBR;
1640 BBSizes[MBB->getNumber()] -= 2;
1641 AdjustBBOffsetsAfter(MBB, -2);
1642 ++NumCBZ;
1643 MadeChange = true;
1644 }
1645 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001646 }
1647 }
1648
1649 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001650}
1651
Evan Chenga1efbbd2009-08-14 00:32:16 +00001652/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1653/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001654bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1655 bool MadeChange = false;
1656
1657 // FIXME: After the tables are shrunk, can we get rid some of the
1658 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001659 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Evan Cheng5657c012009-07-29 02:18:14 +00001660 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1661 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1662 MachineInstr *MI = T2JumpTables[i];
1663 const TargetInstrDesc &TID = MI->getDesc();
1664 unsigned NumOps = TID.getNumOperands();
1665 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1666 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1667 unsigned JTI = JTOP.getIndex();
1668 assert(JTI < JT.size());
1669
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001670 bool ByteOk = true;
1671 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001672 unsigned JTOffset = GetOffsetOf(MI) + 4;
1673 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001674 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1675 MachineBasicBlock *MBB = JTBBs[j];
1676 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001677 // Negative offset is not ok. FIXME: We should change BB layout to make
1678 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001679 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001680 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001681 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001682 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001683 HalfWordOk = false;
1684 if (!ByteOk && !HalfWordOk)
1685 break;
1686 }
1687
1688 if (ByteOk || HalfWordOk) {
1689 MachineBasicBlock *MBB = MI->getParent();
1690 unsigned BaseReg = MI->getOperand(0).getReg();
1691 bool BaseRegKill = MI->getOperand(0).isKill();
1692 if (!BaseRegKill)
1693 continue;
1694 unsigned IdxReg = MI->getOperand(1).getReg();
1695 bool IdxRegKill = MI->getOperand(1).isKill();
1696 MachineBasicBlock::iterator PrevI = MI;
1697 if (PrevI == MBB->begin())
1698 continue;
1699
1700 MachineInstr *AddrMI = --PrevI;
1701 bool OptOk = true;
1702 // Examine the instruction that calculate the jumptable entry address.
1703 // If it's not the one just before the t2BR_JT, we won't delete it, then
1704 // it's not worth doing the optimization.
1705 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1706 const MachineOperand &MO = AddrMI->getOperand(k);
1707 if (!MO.isReg() || !MO.getReg())
1708 continue;
1709 if (MO.isDef() && MO.getReg() != BaseReg) {
1710 OptOk = false;
1711 break;
1712 }
1713 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1714 OptOk = false;
1715 break;
1716 }
1717 }
1718 if (!OptOk)
1719 continue;
1720
Evan Chenga1efbbd2009-08-14 00:32:16 +00001721 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1722 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001723 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001724 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1725 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001726 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001727 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001728
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001729 if (!OptOk)
1730 continue;
1731
1732 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1733 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1734 .addReg(IdxReg, getKillRegState(IdxRegKill))
1735 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1736 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1737 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1738 // is 2-byte aligned. For now, asm printer will fix it up.
1739 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1740 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1741 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1742 OrigSize += TII->GetInstSizeInBytes(MI);
1743
1744 AddrMI->eraseFromParent();
1745 LeaMI->eraseFromParent();
1746 MI->eraseFromParent();
1747
1748 int delta = OrigSize - NewSize;
1749 BBSizes[MBB->getNumber()] -= delta;
1750 AdjustBBOffsetsAfter(MBB, -delta);
1751
1752 ++NumTBs;
1753 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001754 }
1755 }
1756
1757 return MadeChange;
1758}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001759
Jim Grosbach9249efe2009-11-16 18:55:47 +00001760/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1761/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001762bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1763 bool MadeChange = false;
1764
1765 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1766 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1767 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1768 MachineInstr *MI = T2JumpTables[i];
1769 const TargetInstrDesc &TID = MI->getDesc();
1770 unsigned NumOps = TID.getNumOperands();
1771 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1772 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1773 unsigned JTI = JTOP.getIndex();
1774 assert(JTI < JT.size());
1775
1776 // We prefer if target blocks for the jump table come after the jump
1777 // instruction so we can use TB[BH]. Loop through the target blocks
1778 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001779 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001780 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1781 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1782 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001783 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001784
Jim Grosbach08cbda52009-11-16 18:58:52 +00001785 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001786 // The destination precedes the switch. Try to move the block forward
1787 // so we have a positive offset.
1788 MachineBasicBlock *NewBB =
1789 AdjustJTTargetBlockForward(MBB, MI->getParent());
1790 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001791 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001792 MadeChange = true;
1793 }
1794 }
1795 }
1796
1797 return MadeChange;
1798}
1799
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001800MachineBasicBlock *ARMConstantIslands::
1801AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1802{
1803 MachineFunction &MF = *BB->getParent();
1804
Jim Grosbach08cbda52009-11-16 18:58:52 +00001805 // If it's the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001806 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001807 // table that branches back to the actual target. This is a very simple
1808 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001809 MachineBasicBlock *TBB = 0, *FBB = 0;
1810 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001811 SmallVector<MachineOperand, 4> CondPrior;
1812 MachineFunction::iterator BBi = BB;
1813 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001814
Jim Grosbachca215e72009-11-16 17:10:56 +00001815 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001816 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001817
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001818 // If the block ends in an unconditional branch, move it. The prior block
1819 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001820 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001821 if (!B && Cond.empty() && BB != MF.begin() &&
1822 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001823 BB->moveAfter(JTBB);
1824 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001825 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001826 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001827 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001828 ++NumJTMoved;
1829 return NULL;
1830 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001831
1832 // Create a new MBB for the code after the jump BB.
1833 MachineBasicBlock *NewBB =
1834 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1835 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1836 MF.insert(MBBI, NewBB);
1837
1838 // Add an unconditional branch from NewBB to BB.
1839 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1840 // correspond directly to anything in the source.
1841 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1842 BuildMI(NewBB, DebugLoc::getUnknownLoc(), TII->get(ARM::t2B)).addMBB(BB);
1843
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001844 // Update internal data structures to account for the newly inserted MBB.
1845 MF.RenumberBlocks(NewBB);
1846
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001847 // Update the CFG.
1848 NewBB->addSuccessor(BB);
1849 JTBB->removeSuccessor(BB);
1850 JTBB->addSuccessor(NewBB);
1851
Jim Grosbach80697d12009-11-12 17:25:07 +00001852 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001853 return NewBB;
1854}