blob: 17184019443e2f3014b59b3dfedfd47dbef0d293 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.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"
Evan Chenga8e29892007-01-19 07:51:42 +000034using namespace llvm;
35
Evan Chenga1efbbd2009-08-14 00:32:16 +000036STATISTIC(NumCPEs, "Number of constpool entries");
37STATISTIC(NumSplit, "Number of uncond branches inserted");
38STATISTIC(NumCBrFixed, "Number of cond branches fixed");
39STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
40STATISTIC(NumTBs, "Number of table branches generated");
41STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000042STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chenga8e29892007-01-19 07:51:42 +000043
44namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000045 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000046 /// requires constant pool entries to be scattered among the instructions
47 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000048 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000049 /// special instructions.
50 ///
51 /// The terminology used in this pass includes:
52 /// Islands - Clumps of constants placed in the function.
53 /// Water - Potential places where an island could be formed.
54 /// CPE - A constant pool entry that has been placed somewhere, which
55 /// tracks a list of users.
56 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000057 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000058 /// by MBB Number. The two-byte pads required for Thumb alignment are
59 /// counted as part of the following block (i.e., the offset and size for
60 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000061 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000062
Dale Johannesen99c49a42007-02-25 00:47:03 +000063 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000064 /// The two-byte pads required for Thumb alignment are counted as part of
65 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000066 std::vector<unsigned> BBOffsets;
67
Evan Chenga8e29892007-01-19 07:51:42 +000068 /// WaterList - A sorted list of basic blocks where islands could be placed
69 /// (i.e. blocks that don't fall through to the following block, due
70 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000072
Bob Wilson034de5f2009-10-12 18:52:13 +000073 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
74
Evan Chenga8e29892007-01-19 07:51:42 +000075 /// CPUser - One user of a constant pool, keeping the machine instruction
76 /// pointer, the constant pool being referenced, and the max displacement
77 /// allowed from the instruction to the CP.
78 struct CPUser {
79 MachineInstr *MI;
80 MachineInstr *CPEMI;
81 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000082 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000083 bool IsSoImm;
84 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
85 bool neg, bool soimm)
86 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Evan Chenga8e29892007-01-19 07:51:42 +000087 };
Bob Wilson84945262009-05-12 17:09:30 +000088
Evan Chenga8e29892007-01-19 07:51:42 +000089 /// CPUsers - Keep track of all of the machine instructions that use various
90 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000091 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000092
Evan Chengc99ef082007-02-09 20:54:44 +000093 /// CPEntry - One per constant pool entry, keeping the machine instruction
94 /// pointer, the constpool index, and the number of CPUser's which
95 /// reference this entry.
96 struct CPEntry {
97 MachineInstr *CPEMI;
98 unsigned CPI;
99 unsigned RefCount;
100 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
101 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
102 };
103
104 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000105 /// instructions. For each original constpool index (i.e. those that
106 /// existed upon entry to this pass), it keeps a vector of entries.
107 /// Original elements are cloned as we go along; the clones are
108 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000109 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000110
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000111 /// ImmBranch - One per immediate branch, keeping the machine instruction
112 /// pointer, conditional or unconditional, the max displacement,
113 /// and (if isCond is true) the corresponding unconditional branch
114 /// opcode.
115 struct ImmBranch {
116 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000117 unsigned MaxDisp : 31;
118 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000119 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000120 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
121 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000122 };
123
Evan Cheng2706f972007-05-16 05:14:06 +0000124 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000125 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000126 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000127
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000128 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
129 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000130 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000131
Evan Cheng5657c012009-07-29 02:18:14 +0000132 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
133 SmallVector<MachineInstr*, 4> T2JumpTables;
134
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000135 /// HasFarJump - True if any far jump instruction has been emitted during
136 /// the branch fix up pass.
137 bool HasFarJump;
138
Evan Chenga8e29892007-01-19 07:51:42 +0000139 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000140 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000141 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000142 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000143 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000144 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000145 public:
Devang Patel19974732007-05-03 01:11:54 +0000146 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000147 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000148
Evan Cheng5657c012009-07-29 02:18:14 +0000149 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000150
151 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000152 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000153 }
Bob Wilson84945262009-05-12 17:09:30 +0000154
Evan Chenga8e29892007-01-19 07:51:42 +0000155 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000156 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000157 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000158 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000159 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000160 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000161 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000162 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000163 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000164 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000165 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000166 bool LookForWater(CPUser&U, unsigned UserOffset,
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000167 MachineBasicBlock *&NewMBB);
Bob Wilsond637c1a2009-10-12 20:37:23 +0000168 MachineBasicBlock *AcceptWater(water_iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000169 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000170 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000171 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000172 void RemoveDeadCPEMI(MachineInstr *CPEMI);
173 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000174 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000175 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
176 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000177 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000178 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000179 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000180 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000181 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000182 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
183 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
184 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000185 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000186 bool OptimizeThumb2Instructions(MachineFunction &MF);
187 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000188 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000189
Evan Chenga8e29892007-01-19 07:51:42 +0000190 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000191 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000192 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000193 };
Devang Patel19974732007-05-03 01:11:54 +0000194 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000195}
196
Dale Johannesen8593e412007-04-29 19:19:30 +0000197/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000198void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000199 assert(BBOffsets.size() == BBSizes.size());
200 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
201 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000202 if (!isThumb)
203 return;
204#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000205 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000206 MBBI != E; ++MBBI) {
207 MachineBasicBlock *MBB = MBBI;
208 if (!MBB->empty() &&
209 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
210 unsigned MBBId = MBB->getNumber();
211 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
212 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000213 }
214 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000215#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000216}
217
218/// print block size and offset information - debugging
219void ARMConstantIslands::dumpBBs() {
220 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000221 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
222 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000223 }
224}
225
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000226/// createARMConstantIslandPass - returns an instance of the constpool
227/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000228FunctionPass *llvm::createARMConstantIslandPass() {
229 return new ARMConstantIslands();
230}
231
Evan Cheng5657c012009-07-29 02:18:14 +0000232bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
233 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000234
Evan Cheng5657c012009-07-29 02:18:14 +0000235 TII = MF.getTarget().getInstrInfo();
236 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000237 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
238
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000239 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000240 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000241 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000242
243 HasFarJump = false;
244
Evan Chenga8e29892007-01-19 07:51:42 +0000245 // Renumber all of the machine basic blocks in the function, guaranteeing that
246 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000247 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000248
Evan Chengd26b14c2009-07-31 18:28:05 +0000249 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000250 // This is so we can keep exact track of where the alignment padding goes.
251
Evan Chengd26b14c2009-07-31 18:28:05 +0000252 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000253 // aligned.
254 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000255
Evan Chenga8e29892007-01-19 07:51:42 +0000256 // Perform the initial placement of the constant pool entries. To start with,
257 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000258 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000259 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000260 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000261 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000262 AFI->setAlign(2U);
263 }
Bob Wilson84945262009-05-12 17:09:30 +0000264
Evan Chenga8e29892007-01-19 07:51:42 +0000265 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000266 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000267
Evan Chenga8e29892007-01-19 07:51:42 +0000268 // Do the initial scan of the function, building up information about the
269 // sizes of each block, the location of all the water, and finding all of the
270 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000271 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000272 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000273
Evan Chenged884f32007-04-03 23:39:48 +0000274 /// Remove dead constant pool entries.
275 RemoveUnusedCPEntries();
276
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000277 // Iteratively place constant pool entries and fix up branches until there
278 // is no change.
279 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000280 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000281 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000282 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000283 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000284 CPChange |= HandleConstantPoolUser(MF, i);
285 if (CPChange && ++NoCPIters > 30)
286 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000287 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000288
289 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000290 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000291 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
292 if (BRChange && ++NoBRIters > 30)
293 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000294 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000295
296 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000297 break;
298 MadeChange = true;
299 }
Evan Chenged884f32007-04-03 23:39:48 +0000300
Evan Chenga1efbbd2009-08-14 00:32:16 +0000301 // Shrink 32-bit Thumb2 branch, load, and store instructions.
302 if (isThumb2)
303 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000304
Dale Johannesen8593e412007-04-29 19:19:30 +0000305 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000306 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000307
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000308 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
309 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000310 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000311 MadeChange |= UndoLRSpillRestore();
312
Evan Chenga8e29892007-01-19 07:51:42 +0000313 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000314 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000315 WaterList.clear();
316 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000317 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000318 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000319 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000320 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000321
322 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000323}
324
325/// DoInitialPlacement - Perform the initial placement of the constant pool
326/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000327void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000328 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000329 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000330 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
331 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000332
Evan Chenga8e29892007-01-19 07:51:42 +0000333 // Add all of the constants from the constant pool to the end block, use an
334 // identity mapping of CPI's to CPE's.
335 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000336 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000337
Evan Cheng5657c012009-07-29 02:18:14 +0000338 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000339 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000340 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000341 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
342 // we would have to pad them out or something so that instructions stay
343 // aligned.
344 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
345 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000346 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000347 .addImm(i).addConstantPoolIndex(i).addImm(Size);
348 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000349
350 // Add a new CPEntry, but no corresponding CPUser yet.
351 std::vector<CPEntry> CPEs;
352 CPEs.push_back(CPEntry(CPEMI, i));
353 CPEntries.push_back(CPEs);
354 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000355 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
356 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000357 }
358}
359
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000360/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000361/// into the block immediately after it.
362static bool BBHasFallthrough(MachineBasicBlock *MBB) {
363 // Get the next machine basic block in the function.
364 MachineFunction::iterator MBBI = MBB;
365 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
366 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000367
Evan Chenga8e29892007-01-19 07:51:42 +0000368 MachineBasicBlock *NextBB = next(MBBI);
369 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
370 E = MBB->succ_end(); I != E; ++I)
371 if (*I == NextBB)
372 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000373
Evan Chenga8e29892007-01-19 07:51:42 +0000374 return false;
375}
376
Evan Chengc99ef082007-02-09 20:54:44 +0000377/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
378/// look up the corresponding CPEntry.
379ARMConstantIslands::CPEntry
380*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
381 const MachineInstr *CPEMI) {
382 std::vector<CPEntry> &CPEs = CPEntries[CPI];
383 // Number of entries per constpool index should be small, just do a
384 // linear search.
385 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
386 if (CPEs[i].CPEMI == CPEMI)
387 return &CPEs[i];
388 }
389 return NULL;
390}
391
Evan Chenga8e29892007-01-19 07:51:42 +0000392/// InitialFunctionScan - Do the initial scan of the function, building up
393/// information about the sizes of each block, the location of all the water,
394/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000395void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000396 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000397 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000398 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000399 MBBI != E; ++MBBI) {
400 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000401
Evan Chenga8e29892007-01-19 07:51:42 +0000402 // If this block doesn't fall through into the next MBB, then this is
403 // 'water' that a constant pool island could be placed.
404 if (!BBHasFallthrough(&MBB))
405 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000406
Evan Chenga8e29892007-01-19 07:51:42 +0000407 unsigned MBBSize = 0;
408 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
409 I != E; ++I) {
410 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000411 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000412
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000413 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000414 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000415 bool isCond = false;
416 unsigned Bits = 0;
417 unsigned Scale = 1;
418 int UOpc = Opc;
419 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000420 default:
421 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000422 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000423 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000424 // be right, functions containing these must be 4-byte aligned.
425 AFI->setAlign(2U);
426 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000427 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000428 MBBSize += 2; // padding
429 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000430 case ARM::t2BR_JT:
431 T2JumpTables.push_back(I);
432 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000433 case ARM::Bcc:
434 isCond = true;
435 UOpc = ARM::B;
436 // Fallthrough
437 case ARM::B:
438 Bits = 24;
439 Scale = 4;
440 break;
441 case ARM::tBcc:
442 isCond = true;
443 UOpc = ARM::tB;
444 Bits = 8;
445 Scale = 2;
446 break;
447 case ARM::tB:
448 Bits = 11;
449 Scale = 2;
450 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000451 case ARM::t2Bcc:
452 isCond = true;
453 UOpc = ARM::t2B;
454 Bits = 20;
455 Scale = 2;
456 break;
457 case ARM::t2B:
458 Bits = 24;
459 Scale = 2;
460 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000461 }
Evan Chengb43216e2007-02-01 10:16:15 +0000462
463 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000464 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000465 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000466 }
467
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000468 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
469 PushPopMIs.push_back(I);
470
Evan Chengd3d9d662009-07-23 18:27:47 +0000471 if (Opc == ARM::CONSTPOOL_ENTRY)
472 continue;
473
Evan Chenga8e29892007-01-19 07:51:42 +0000474 // Scan the instructions for constant pool operands.
475 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000476 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000477 // We found one. The addressing mode tells us the max displacement
478 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000479
Evan Chenga8e29892007-01-19 07:51:42 +0000480 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000481 unsigned Bits = 0;
482 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000483 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000484 bool IsSoImm = false;
485
486 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000487 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000488 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000489 break;
490
491 // Taking the address of a CP entry.
492 case ARM::LEApcrel:
493 // This takes a SoImm, which is 8 bit immediate rotated. We'll
494 // pretend the maximum offset is 255 * 4. Since each instruction
495 // 4 byte wide, this is always correct. We'llc heck for other
496 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000497 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000498 Scale = 4;
499 NegOk = true;
500 IsSoImm = true;
501 break;
502 case ARM::t2LEApcrel:
503 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000504 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000505 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000506 case ARM::tLEApcrel:
507 Bits = 8;
508 Scale = 4;
509 break;
510
511 case ARM::LDR:
512 case ARM::LDRcp:
513 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000514 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000515 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000516 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000517
518 case ARM::tLDRpci:
519 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000520 Bits = 8;
521 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000522 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000523
524 case ARM::FLDD:
525 case ARM::FLDS:
526 Bits = 8;
527 Scale = 4; // +-(offset_8*4)
528 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000529 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000530 }
Evan Chengb43216e2007-02-01 10:16:15 +0000531
Evan Chenga8e29892007-01-19 07:51:42 +0000532 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000533 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000534 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000535 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000536 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000537
538 // Increment corresponding CPEntry reference count.
539 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
540 assert(CPE && "Cannot find a corresponding CPEntry!");
541 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000542
Evan Chenga8e29892007-01-19 07:51:42 +0000543 // Instructions can only use one CP entry, don't bother scanning the
544 // rest of the operands.
545 break;
546 }
547 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000548
Dale Johannesen8593e412007-04-29 19:19:30 +0000549 // In thumb mode, if this block is a constpool island, we may need padding
550 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000551 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000552 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000553 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
554 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000555 MBBSize += 2;
556
Evan Chenga8e29892007-01-19 07:51:42 +0000557 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000558 BBOffsets.push_back(Offset);
559 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000560 }
561}
562
Evan Chenga8e29892007-01-19 07:51:42 +0000563/// GetOffsetOf - Return the current offset of the specified machine instruction
564/// from the start of the function. This offset changes as stuff is moved
565/// around inside the function.
566unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
567 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000568
Evan Chenga8e29892007-01-19 07:51:42 +0000569 // The offset is composed of two things: the sum of the sizes of all MBB's
570 // before this instruction's block, and the offset from the start of the block
571 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000572 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000573
Dale Johannesen8593e412007-04-29 19:19:30 +0000574 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
575 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000576 if (isThumb &&
577 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000578 Offset%4 != 0)
579 Offset += 2;
580
Evan Chenga8e29892007-01-19 07:51:42 +0000581 // Sum instructions before MI in MBB.
582 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
583 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
584 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000585 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000586 }
587}
588
589/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
590/// ID.
591static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
592 const MachineBasicBlock *RHS) {
593 return LHS->getNumber() < RHS->getNumber();
594}
595
596/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
597/// machine function, it upsets all of the block numbers. Renumber the blocks
598/// and update the arrays that parallel this numbering.
599void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
600 // Renumber the MBB's to keep them consequtive.
601 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000602
Evan Chenga8e29892007-01-19 07:51:42 +0000603 // Insert a size into BBSizes to align it properly with the (newly
604 // renumbered) block numbers.
605 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000606
607 // Likewise for BBOffsets.
608 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000609
610 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000611 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000612 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000613 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
614 CompareMBBNumbers);
615 WaterList.insert(IP, NewBB);
616}
617
618
619/// Split the basic block containing MI into two blocks, which are joined by
620/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000621/// account for this change and returns the newly created block.
622MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000623 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000624 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000625
626 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000627 MachineBasicBlock *NewBB =
628 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000629 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000630 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000631
Evan Chenga8e29892007-01-19 07:51:42 +0000632 // Splice the instructions starting with MI over to NewBB.
633 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000634
Evan Chenga8e29892007-01-19 07:51:42 +0000635 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000636 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000637 // There doesn't seem to be meaningful DebugInfo available; this doesn't
638 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000639 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
640 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000641 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000642
Evan Chenga8e29892007-01-19 07:51:42 +0000643 // Update the CFG. All succs of OrigBB are now succs of NewBB.
644 while (!OrigBB->succ_empty()) {
645 MachineBasicBlock *Succ = *OrigBB->succ_begin();
646 OrigBB->removeSuccessor(Succ);
647 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000648
Evan Chenga8e29892007-01-19 07:51:42 +0000649 // This pass should be run after register allocation, so there should be no
650 // PHI nodes to update.
651 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
652 && "PHI nodes should be eliminated by now!");
653 }
Bob Wilson84945262009-05-12 17:09:30 +0000654
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // OrigBB branches to NewBB.
656 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000657
Evan Chenga8e29892007-01-19 07:51:42 +0000658 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000659 // This is almost the same as UpdateForInsertedWaterBlock, except that
660 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000661 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000662
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000663 // Insert a size into BBSizes to align it properly with the (newly
664 // renumbered) block numbers.
665 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000666
Dale Johannesen99c49a42007-02-25 00:47:03 +0000667 // Likewise for BBOffsets.
668 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
669
Bob Wilson84945262009-05-12 17:09:30 +0000670 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000671 // available water after it (but not if it's already there, which happens
672 // when splitting before a conditional branch that is followed by an
673 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000674 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000675 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
676 CompareMBBNumbers);
677 MachineBasicBlock* WaterBB = *IP;
678 if (WaterBB == OrigBB)
679 WaterList.insert(next(IP), NewBB);
680 else
681 WaterList.insert(IP, OrigBB);
682
Dale Johannesen8593e412007-04-29 19:19:30 +0000683 // Figure out how large the first NewMBB is. (It cannot
684 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000685 unsigned NewBBSize = 0;
686 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
687 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000688 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000689
Dale Johannesen99c49a42007-02-25 00:47:03 +0000690 unsigned OrigBBI = OrigBB->getNumber();
691 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000692 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000693 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000694
Evan Chenga8e29892007-01-19 07:51:42 +0000695 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000696 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000697 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000698 BBSizes[OrigBBI] -= NewBBSize - delta;
699
700 // ...and adjust BBOffsets for NewBB accordingly.
701 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
702
703 // All BBOffsets following these blocks must be modified.
704 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000705
706 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000707}
708
Dale Johannesen8593e412007-04-29 19:19:30 +0000709/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000710/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000711/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000712bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000713 unsigned TrialOffset, unsigned MaxDisp,
714 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000715 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
716 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000717 // Effectively, the valid range of displacements is 2 bytes smaller for such
718 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000719 unsigned TotalAdj = 0;
720 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000721 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000722 TotalAdj = 2;
723 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000724 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000725 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000726 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000727 TotalAdj += 2;
728 }
729
730 // In Thumb2 mode, later branch adjustments can shift instructions up and
731 // cause alignment change. In the worst case scenario this can cause the
732 // user's effective address to be subtracted by 2 and the CPE's address to
733 // be plus 2.
734 if (isThumb2 && TotalAdj != 4)
735 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000736
Dale Johannesen99c49a42007-02-25 00:47:03 +0000737 if (UserOffset <= TrialOffset) {
738 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000739 if (TrialOffset - UserOffset <= MaxDisp)
740 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000741 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000742 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000743 if (UserOffset - TrialOffset <= MaxDisp)
744 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000745 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000746 }
747 return false;
748}
749
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000750/// WaterIsInRange - Returns true if a CPE placed after the specified
751/// Water (a basic block) will be in range for the specific MI.
752
753bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000754 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000755 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000756 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000757 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000758
Dale Johannesend959aa42007-04-02 20:31:06 +0000759 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000760 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000761 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000762 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000763
Evan Chengd3d9d662009-07-23 18:27:47 +0000764 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000765}
766
767/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000768/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000769bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000770 MachineInstr *CPEMI, unsigned MaxDisp,
771 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000772 unsigned CPEOffset = GetOffsetOf(CPEMI);
773 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000774
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000775 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000776 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
777 << " max delta=" << MaxDisp
778 << " insn address=" << UserOffset
779 << " CPE address=" << CPEOffset
780 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000781 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000782
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000783 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000784}
785
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000786#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000787/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
788/// unconditionally branches to its only successor.
789static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
790 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
791 return false;
792
793 MachineBasicBlock *Succ = *MBB->succ_begin();
794 MachineBasicBlock *Pred = *MBB->pred_begin();
795 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000796 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
797 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000798 return PredMI->getOperand(0).getMBB() == Succ;
799 return false;
800}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000801#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000802
Bob Wilson84945262009-05-12 17:09:30 +0000803void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000804 int delta) {
805 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000806 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
807 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000808 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000809 // If some existing blocks have padding, adjust the padding as needed, a
810 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000811 if (!isThumb)
812 continue;
813 MachineBasicBlock *MBB = MBBI;
814 if (!MBB->empty()) {
815 // Constant pool entries require padding.
816 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000817 unsigned OldOffset = BBOffsets[i] - delta;
818 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000819 // add new padding
820 BBSizes[i] += 2;
821 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000822 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000823 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000824 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000825 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000826 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000827 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000828 // Thumb1 jump tables require padding. They should be at the end;
829 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000830 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000831 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000832 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
833 unsigned OldMIOffset = NewMIOffset - delta;
834 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000835 // remove existing padding
836 BBSizes[i] -= 2;
837 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000838 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000839 // add new padding
840 BBSizes[i] += 2;
841 delta += 2;
842 }
843 }
844 if (delta==0)
845 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000846 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000847 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000848 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000849}
850
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000851/// DecrementOldEntry - find the constant pool entry with index CPI
852/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000853/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000854/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000855
Evan Chenged884f32007-04-03 23:39:48 +0000856bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000857 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000858 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
859 assert(CPE && "Unexpected!");
860 if (--CPE->RefCount == 0) {
861 RemoveDeadCPEMI(CPEMI);
862 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000863 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000864 return true;
865 }
866 return false;
867}
868
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000869/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
870/// if not, see if an in-range clone of the CPE is in range, and if so,
871/// change the data structures so the user references the clone. Returns:
872/// 0 = no existing entry found
873/// 1 = entry found, and there were no code insertions or deletions
874/// 2 = entry found, and there were code insertions or deletions
875int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
876{
877 MachineInstr *UserMI = U.MI;
878 MachineInstr *CPEMI = U.CPEMI;
879
880 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000881 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000882 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000884 }
885
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000887 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888 std::vector<CPEntry> &CPEs = CPEntries[CPI];
889 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
890 // We already tried this one
891 if (CPEs[i].CPEMI == CPEMI)
892 continue;
893 // Removing CPEs can leave empty entries, skip
894 if (CPEs[i].CPEMI == NULL)
895 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000896 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000897 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
898 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000899 // Point the CPUser node to the replacement
900 U.CPEMI = CPEs[i].CPEMI;
901 // Change the CPI in the instruction operand to refer to the clone.
902 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000903 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000904 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000905 break;
906 }
907 // Adjust the refcount of the clone...
908 CPEs[i].RefCount++;
909 // ...and the original. If we didn't remove the old entry, none of the
910 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000911 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000912 }
913 }
914 return 0;
915}
916
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000917/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
918/// the specific unconditional branch instruction.
919static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000920 switch (Opc) {
921 case ARM::tB:
922 return ((1<<10)-1)*2;
923 case ARM::t2B:
924 return ((1<<23)-1)*2;
925 default:
926 break;
927 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000928
David Goodwin5e47a9a2009-06-30 18:04:13 +0000929 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000930}
931
Dale Johannesen8593e412007-04-29 19:19:30 +0000932/// AcceptWater - Small amount of common code factored out of the following.
Bob Wilsond637c1a2009-10-12 20:37:23 +0000933///
934MachineBasicBlock *ARMConstantIslands::AcceptWater(water_iterator IP) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000935 DEBUG(errs() << "found water in range\n");
Bob Wilson4796ba22009-10-13 17:29:13 +0000936 MachineBasicBlock *WaterBB = *IP;
Dale Johannesen8593e412007-04-29 19:19:30 +0000937 // Remove the original WaterList entry; we want subsequent
938 // insertions in this vicinity to go after the one we're
939 // about to insert. This considerably reduces the number
940 // of times we have to move the same CPE more than once.
941 WaterList.erase(IP);
942 // CPE goes before following block (NewMBB).
Bob Wilson4796ba22009-10-13 17:29:13 +0000943 return next(MachineFunction::iterator(WaterBB));
Dale Johannesen8593e412007-04-29 19:19:30 +0000944}
945
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000946/// LookForWater - look for an existing entry in the WaterList in which
947/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000948/// Returns true if found, false if not. If it returns true, NewMBB
Bob Wilsonf98032e2009-10-12 21:23:15 +0000949/// is set to the WaterList entry. For Thumb, prefer water that will not
950/// introduce padding to water that will. To ensure that this pass
951/// terminates, the CPE location for a particular CPUser is only allowed to
952/// move to a lower address, so search backward from the end of the list and
953/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000954bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000955 MachineBasicBlock *&NewMBB) {
Bob Wilson3b757352009-10-12 19:04:03 +0000956 if (WaterList.empty())
957 return false;
958
Bob Wilson32c50e82009-10-12 20:45:53 +0000959 bool FoundWaterThatWouldPad = false;
960 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000961 for (water_iterator IP = prior(WaterList.end()),
962 B = WaterList.begin();; --IP) {
963 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonf98032e2009-10-12 21:23:15 +0000964 // Check if water is in range and at a lower address than the current one.
965 if (WaterIsInRange(UserOffset, WaterBB, U) &&
966 WaterBB->getNumber() < U.CPEMI->getParent()->getNumber()) {
Bob Wilson3b757352009-10-12 19:04:03 +0000967 unsigned WBBId = WaterBB->getNumber();
968 if (isThumb &&
969 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
970 // This is valid Water, but would introduce padding. Remember
971 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +0000972 if (!FoundWaterThatWouldPad) {
973 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +0000974 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000975 }
Bob Wilson3b757352009-10-12 19:04:03 +0000976 } else {
Bob Wilsond637c1a2009-10-12 20:37:23 +0000977 NewMBB = AcceptWater(IP);
Bob Wilson3b757352009-10-12 19:04:03 +0000978 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +0000979 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000980 }
Bob Wilson3b757352009-10-12 19:04:03 +0000981 if (IP == B)
982 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000983 }
Bob Wilson32c50e82009-10-12 20:45:53 +0000984 if (FoundWaterThatWouldPad) {
Bob Wilsond637c1a2009-10-12 20:37:23 +0000985 NewMBB = AcceptWater(IPThatWouldPad);
Dale Johannesen8593e412007-04-29 19:19:30 +0000986 return true;
987 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000988 return false;
989}
990
Bob Wilson84945262009-05-12 17:09:30 +0000991/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000992/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
993/// block is used if in range, and the conditional branch munged so control
994/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +0000995/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000996/// block following which the new island can be inserted (the WaterList
997/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +0000998void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +0000999 unsigned UserOffset,
1000 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001001 CPUser &U = CPUsers[CPUserIndex];
1002 MachineInstr *UserMI = U.MI;
1003 MachineInstr *CPEMI = U.CPEMI;
1004 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001005 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001006 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001007 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001008
Bob Wilson36fa5322009-10-15 05:10:36 +00001009 // If the block does not end in an unconditional branch already, and if the
1010 // end of the block is within range, make new water there. (The addition
1011 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1012 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001013 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001014 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001015 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1016 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001017 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018 if (&UserMBB->back() == UserMI)
1019 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001020 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001021 // Add an unconditional branch from UserMBB to fallthrough block.
1022 // Record it for branch lengthening; this new branch will not get out of
1023 // range, but if the preceding conditional branch is out of range, the
1024 // targets will be exchanged, and the altered branch may be out of
1025 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001026 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001027 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001028 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001029 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001030 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001031 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001032 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 BBSizes[UserMBB->getNumber()] += delta;
1034 AdjustBBOffsetsAfter(UserMBB, delta);
1035 } else {
1036 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001037 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001038 // and constant pool entries are 4 bytes: if instruction I references
1039 // island CPE, and instruction I+1 references CPE', it will
1040 // not work well to put CPE as far forward as possible, since then
1041 // CPE' cannot immediately follow it (that location is 2 bytes
1042 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001043 // a new island. So, we make a first guess, then walk through the
1044 // instructions between the one currently being looked at and the
1045 // possible insertion point, and make sure any other instructions
1046 // that reference CPEs will be able to use the same island area;
1047 // if not, we back up the insertion point.
1048
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001049 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001050 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001051 // island is handled inside OffsetIsInRange.
1052 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001053 // This could point off the end of the block if we've already got
1054 // constant pool entries following this block; only the last one is
1055 // in the water list. Back past any possible branches (allow for a
1056 // conditional and a maximally long unconditional).
1057 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001058 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001059 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001060 unsigned EndInsertOffset = BaseInsertOffset +
1061 CPEMI->getOperand(2).getImm();
1062 MachineBasicBlock::iterator MI = UserMI;
1063 ++MI;
1064 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001065 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001066 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001067 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001068 MI = next(MI)) {
1069 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001070 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001071 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001072 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1073 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1074 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001075 }
1076 // This is overly conservative, as we don't account for CPEMIs
1077 // being reused within the block, but it doesn't matter much.
1078 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1079 CPUIndex++;
1080 }
1081 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001082 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001083 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001084 }
1085}
1086
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001087/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001088/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001089/// place in-range. Return true if we changed any addresses (thus must run
1090/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001091bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001092 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001093 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001094 MachineInstr *UserMI = U.MI;
1095 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001096 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001097 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001098 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001099 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001100 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001102
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001103 // See if the current entry is within range, or there is a clone of it
1104 // in range.
1105 int result = LookForExistingCPEntry(U, UserOffset);
1106 if (result==1) return false;
1107 else if (result==2) return true;
1108
1109 // No existing clone of this CPE is within range.
1110 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001111 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001112
Bob Wilsonf98032e2009-10-12 21:23:15 +00001113 // Look for water where we can place this CPE.
Bob Wilson9d16f2c2009-10-12 19:01:12 +00001114 if (!LookForWater(U, UserOffset, NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001115 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001116 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001117 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001118 }
1119
1120 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001121 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1122 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001123
1124 // Update internal data structures to account for the newly inserted MBB.
1125 UpdateForInsertedWaterBlock(NewIsland);
1126
1127 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001128 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001129
1130 // Now that we have an island to add the CPE to, clone the original CPE and
1131 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001132 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1133 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001134 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001135 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001136 NumCPEs++;
1137
Dale Johannesen8593e412007-04-29 19:19:30 +00001138 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001139 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001140 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001141 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001142 // Increase the size of the island block to account for the new entry.
1143 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001144 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001145
Evan Chenga8e29892007-01-19 07:51:42 +00001146 // Finally, change the CPI in the instruction operand to be ID.
1147 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001148 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001149 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001150 break;
1151 }
Bob Wilson84945262009-05-12 17:09:30 +00001152
Chris Lattner705e07f2009-08-23 03:41:05 +00001153 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1154 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001155
Evan Chenga8e29892007-01-19 07:51:42 +00001156 return true;
1157}
1158
Evan Chenged884f32007-04-03 23:39:48 +00001159/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1160/// sizes and offsets of impacted basic blocks.
1161void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1162 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001163 unsigned Size = CPEMI->getOperand(2).getImm();
1164 CPEMI->eraseFromParent();
1165 BBSizes[CPEBB->getNumber()] -= Size;
1166 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001167 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001168 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001169 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001170 // empty, so fix this.
1171 // All succeeding offsets have the current size value added in, fix this.
1172 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001173 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001174 BBSizes[CPEBB->getNumber()] = 0;
1175 }
Evan Chenged884f32007-04-03 23:39:48 +00001176 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001177 AdjustBBOffsetsAfter(CPEBB, -Size);
1178 // An island has only one predecessor BB and one successor BB. Check if
1179 // this BB's predecessor jumps directly to this BB's successor. This
1180 // shouldn't happen currently.
1181 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1182 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001183}
1184
1185/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1186/// are zero.
1187bool ARMConstantIslands::RemoveUnusedCPEntries() {
1188 unsigned MadeChange = false;
1189 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1190 std::vector<CPEntry> &CPEs = CPEntries[i];
1191 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1192 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1193 RemoveDeadCPEMI(CPEs[j].CPEMI);
1194 CPEs[j].CPEMI = NULL;
1195 MadeChange = true;
1196 }
1197 }
Bob Wilson84945262009-05-12 17:09:30 +00001198 }
Evan Chenged884f32007-04-03 23:39:48 +00001199 return MadeChange;
1200}
1201
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001202/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001203/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001204bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1205 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001206 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001207 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001208 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001209
Chris Lattner705e07f2009-08-23 03:41:05 +00001210 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1211 << " from BB#" << MI->getParent()->getNumber()
1212 << " max delta=" << MaxDisp
1213 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1214 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001215
Dale Johannesen8593e412007-04-29 19:19:30 +00001216 if (BrOffset <= DestOffset) {
1217 // Branch before the Dest.
1218 if (DestOffset-BrOffset <= MaxDisp)
1219 return true;
1220 } else {
1221 if (BrOffset-DestOffset <= MaxDisp)
1222 return true;
1223 }
1224 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001225}
1226
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001227/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1228/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001229bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001230 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001231 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001232
Evan Chengc0dbec72007-01-31 19:57:44 +00001233 // Check to see if the DestBB is already in-range.
1234 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001235 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001236
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001237 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001238 return FixUpUnconditionalBr(MF, Br);
1239 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001240}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001241
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001242/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1243/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001244/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001245/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001246bool
Evan Cheng5657c012009-07-29 02:18:14 +00001247ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001248 MachineInstr *MI = Br.MI;
1249 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001250 if (!isThumb1)
1251 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001252
1253 // Use BL to implement far jump.
1254 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001255 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001256 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001257 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001258 HasFarJump = true;
1259 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001260
Chris Lattner705e07f2009-08-23 03:41:05 +00001261 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001262
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001263 return true;
1264}
1265
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001266/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001267/// far away to fit in its displacement field. It is converted to an inverse
1268/// conditional branch + an unconditional branch to the destination.
1269bool
Evan Cheng5657c012009-07-29 02:18:14 +00001270ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001271 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001272 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001273
Bob Wilson39bf0512009-05-12 17:35:29 +00001274 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001275 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001276 // blt L1
1277 // =>
1278 // bge L2
1279 // b L1
1280 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001281 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001282 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001283 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001284
1285 // If the branch is at the end of its MBB and that has a fall-through block,
1286 // direct the updated conditional branch to the fall-through block. Otherwise,
1287 // split the MBB before the next instruction.
1288 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001289 MachineInstr *BMI = &MBB->back();
1290 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001291
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001292 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001293 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001294 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001295 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001296 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001297 // condition and swap destinations:
1298 // beq L1
1299 // b L2
1300 // =>
1301 // bne L2
1302 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001303 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001304 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001305 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1306 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001307 BMI->getOperand(0).setMBB(DestBB);
1308 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001309 MI->getOperand(1).setImm(CC);
1310 return true;
1311 }
1312 }
1313 }
1314
1315 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001316 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001317 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001318 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001319 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001320 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001321 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1322 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001323 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001324 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001325 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001326 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001327
Chris Lattner893e1c92009-08-23 06:49:22 +00001328 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1329 << " also invert condition and change dest. to BB#"
1330 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001331
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001332 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001333 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001334 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1335 TII->get(MI->getOpcode()))
1336 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001337 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001338 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001339 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001340 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001341 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001342 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001343
1344 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001345 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001346 MI->eraseFromParent();
1347
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001348 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001349 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001350 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001351 return true;
1352}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001353
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001354/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001355/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1356/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001357bool ARMConstantIslands::UndoLRSpillRestore() {
1358 bool MadeChange = false;
1359 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1360 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001361 // First two operands are predicates, the third is a zero since there
1362 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001363 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001364 MI->getOperand(3).getReg() == ARM::PC &&
1365 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001366 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001367 MI->eraseFromParent();
1368 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001369 }
1370 }
1371 return MadeChange;
1372}
Evan Cheng5657c012009-07-29 02:18:14 +00001373
Evan Chenga1efbbd2009-08-14 00:32:16 +00001374bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1375 bool MadeChange = false;
1376
1377 // Shrink ADR and LDR from constantpool.
1378 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1379 CPUser &U = CPUsers[i];
1380 unsigned Opcode = U.MI->getOpcode();
1381 unsigned NewOpc = 0;
1382 unsigned Scale = 1;
1383 unsigned Bits = 0;
1384 switch (Opcode) {
1385 default: break;
1386 case ARM::t2LEApcrel:
1387 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1388 NewOpc = ARM::tLEApcrel;
1389 Bits = 8;
1390 Scale = 4;
1391 }
1392 break;
1393 case ARM::t2LDRpci:
1394 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1395 NewOpc = ARM::tLDRpci;
1396 Bits = 8;
1397 Scale = 4;
1398 }
1399 break;
1400 }
1401
1402 if (!NewOpc)
1403 continue;
1404
1405 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1406 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1407 // FIXME: Check if offset is multiple of scale if scale is not 4.
1408 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1409 U.MI->setDesc(TII->get(NewOpc));
1410 MachineBasicBlock *MBB = U.MI->getParent();
1411 BBSizes[MBB->getNumber()] -= 2;
1412 AdjustBBOffsetsAfter(MBB, -2);
1413 ++NumT2CPShrunk;
1414 MadeChange = true;
1415 }
1416 }
1417
Evan Chenga1efbbd2009-08-14 00:32:16 +00001418 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001419 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001420 return MadeChange;
1421}
1422
1423bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001424 bool MadeChange = false;
1425
1426 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1427 ImmBranch &Br = ImmBranches[i];
1428 unsigned Opcode = Br.MI->getOpcode();
1429 unsigned NewOpc = 0;
1430 unsigned Scale = 1;
1431 unsigned Bits = 0;
1432 switch (Opcode) {
1433 default: break;
1434 case ARM::t2B:
1435 NewOpc = ARM::tB;
1436 Bits = 11;
1437 Scale = 2;
1438 break;
1439 case ARM::t2Bcc:
1440 NewOpc = ARM::tBcc;
1441 Bits = 8;
1442 Scale = 2;
1443 break;
1444 }
1445 if (!NewOpc)
1446 continue;
1447
1448 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1449 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1450 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1451 Br.MI->setDesc(TII->get(NewOpc));
1452 MachineBasicBlock *MBB = Br.MI->getParent();
1453 BBSizes[MBB->getNumber()] -= 2;
1454 AdjustBBOffsetsAfter(MBB, -2);
1455 ++NumT2BrShrunk;
1456 MadeChange = true;
1457 }
1458 }
1459
1460 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001461}
1462
1463
1464/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1465/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001466bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1467 bool MadeChange = false;
1468
1469 // FIXME: After the tables are shrunk, can we get rid some of the
1470 // constantpool tables?
1471 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1472 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1473 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1474 MachineInstr *MI = T2JumpTables[i];
1475 const TargetInstrDesc &TID = MI->getDesc();
1476 unsigned NumOps = TID.getNumOperands();
1477 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1478 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1479 unsigned JTI = JTOP.getIndex();
1480 assert(JTI < JT.size());
1481
1482 bool ByteOk = true;
1483 bool HalfWordOk = true;
1484 unsigned JTOffset = GetOffsetOf(MI) + 4;
1485 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1486 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1487 MachineBasicBlock *MBB = JTBBs[j];
1488 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001489 // Negative offset is not ok. FIXME: We should change BB layout to make
1490 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001491 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001492 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001493 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001494 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001495 HalfWordOk = false;
1496 if (!ByteOk && !HalfWordOk)
1497 break;
1498 }
1499
1500 if (ByteOk || HalfWordOk) {
1501 MachineBasicBlock *MBB = MI->getParent();
1502 unsigned BaseReg = MI->getOperand(0).getReg();
1503 bool BaseRegKill = MI->getOperand(0).isKill();
1504 if (!BaseRegKill)
1505 continue;
1506 unsigned IdxReg = MI->getOperand(1).getReg();
1507 bool IdxRegKill = MI->getOperand(1).isKill();
1508 MachineBasicBlock::iterator PrevI = MI;
1509 if (PrevI == MBB->begin())
1510 continue;
1511
1512 MachineInstr *AddrMI = --PrevI;
1513 bool OptOk = true;
1514 // Examine the instruction that calculate the jumptable entry address.
1515 // If it's not the one just before the t2BR_JT, we won't delete it, then
1516 // it's not worth doing the optimization.
1517 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1518 const MachineOperand &MO = AddrMI->getOperand(k);
1519 if (!MO.isReg() || !MO.getReg())
1520 continue;
1521 if (MO.isDef() && MO.getReg() != BaseReg) {
1522 OptOk = false;
1523 break;
1524 }
1525 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1526 OptOk = false;
1527 break;
1528 }
1529 }
1530 if (!OptOk)
1531 continue;
1532
Evan Chenga1efbbd2009-08-14 00:32:16 +00001533 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1534 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001535 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001536 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1537 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001538 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001539 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001540
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001541 if (!OptOk)
1542 continue;
1543
1544 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1545 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1546 .addReg(IdxReg, getKillRegState(IdxRegKill))
1547 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1548 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1549 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1550 // is 2-byte aligned. For now, asm printer will fix it up.
1551 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1552 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1553 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1554 OrigSize += TII->GetInstSizeInBytes(MI);
1555
1556 AddrMI->eraseFromParent();
1557 LeaMI->eraseFromParent();
1558 MI->eraseFromParent();
1559
1560 int delta = OrigSize - NewSize;
1561 BBSizes[MBB->getNumber()] -= delta;
1562 AdjustBBOffsetsAfter(MBB, -delta);
1563
1564 ++NumTBs;
1565 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001566 }
1567 }
1568
1569 return MadeChange;
1570}