blob: fcbee4d74a7e132e70dda836b105145eac9d498f [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
Evan Chenga8e29892007-01-19 07:51:42 +000073 /// CPUser - One user of a constant pool, keeping the machine instruction
74 /// pointer, the constant pool being referenced, and the max displacement
75 /// allowed from the instruction to the CP.
76 struct CPUser {
77 MachineInstr *MI;
78 MachineInstr *CPEMI;
79 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000080 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000081 bool IsSoImm;
82 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
83 bool neg, bool soimm)
84 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Evan Chenga8e29892007-01-19 07:51:42 +000085 };
Bob Wilson84945262009-05-12 17:09:30 +000086
Evan Chenga8e29892007-01-19 07:51:42 +000087 /// CPUsers - Keep track of all of the machine instructions that use various
88 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000089 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000090
Evan Chengc99ef082007-02-09 20:54:44 +000091 /// CPEntry - One per constant pool entry, keeping the machine instruction
92 /// pointer, the constpool index, and the number of CPUser's which
93 /// reference this entry.
94 struct CPEntry {
95 MachineInstr *CPEMI;
96 unsigned CPI;
97 unsigned RefCount;
98 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
99 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
100 };
101
102 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000103 /// instructions. For each original constpool index (i.e. those that
104 /// existed upon entry to this pass), it keeps a vector of entries.
105 /// Original elements are cloned as we go along; the clones are
106 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000107 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000108
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000109 /// ImmBranch - One per immediate branch, keeping the machine instruction
110 /// pointer, conditional or unconditional, the max displacement,
111 /// and (if isCond is true) the corresponding unconditional branch
112 /// opcode.
113 struct ImmBranch {
114 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000115 unsigned MaxDisp : 31;
116 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000117 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000118 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
119 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000120 };
121
Evan Cheng2706f972007-05-16 05:14:06 +0000122 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000123 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000124 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000125
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000126 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
127 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000128 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000129
Evan Cheng5657c012009-07-29 02:18:14 +0000130 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
131 SmallVector<MachineInstr*, 4> T2JumpTables;
132
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000133 /// HasFarJump - True if any far jump instruction has been emitted during
134 /// the branch fix up pass.
135 bool HasFarJump;
136
Evan Chenga8e29892007-01-19 07:51:42 +0000137 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000138 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000139 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000140 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000141 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000142 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000143 public:
Devang Patel19974732007-05-03 01:11:54 +0000144 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000145 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000146
Evan Cheng5657c012009-07-29 02:18:14 +0000147 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000148
149 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000150 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000151 }
Bob Wilson84945262009-05-12 17:09:30 +0000152
Evan Chenga8e29892007-01-19 07:51:42 +0000153 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000154 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000155 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000156 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000157 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000158 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000159 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000160 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000161 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000162 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000163 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000164 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000165 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000166 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000167 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000168 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
169 MachineBasicBlock** NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000170 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000171 void RemoveDeadCPEMI(MachineInstr *CPEMI);
172 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000173 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000174 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
175 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000176 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000177 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000178 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000179 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000180 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000181 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
182 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
183 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000184 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000185 bool OptimizeThumb2Instructions(MachineFunction &MF);
186 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000187 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000188
Evan Chenga8e29892007-01-19 07:51:42 +0000189 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000190 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000191 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000192 };
Devang Patel19974732007-05-03 01:11:54 +0000193 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000194}
195
Dale Johannesen8593e412007-04-29 19:19:30 +0000196/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000197void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000198 assert(BBOffsets.size() == BBSizes.size());
199 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
200 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000201 if (!isThumb)
202 return;
203#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000204 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000205 MBBI != E; ++MBBI) {
206 MachineBasicBlock *MBB = MBBI;
207 if (!MBB->empty() &&
208 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
209 unsigned MBBId = MBB->getNumber();
210 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
211 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000212 }
213 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000214#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000215}
216
217/// print block size and offset information - debugging
218void ARMConstantIslands::dumpBBs() {
219 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000220 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000221 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000222 }
223}
224
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000225/// createARMConstantIslandPass - returns an instance of the constpool
226/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000227FunctionPass *llvm::createARMConstantIslandPass() {
228 return new ARMConstantIslands();
229}
230
Evan Cheng5657c012009-07-29 02:18:14 +0000231bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
232 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000233
Evan Cheng5657c012009-07-29 02:18:14 +0000234 TII = MF.getTarget().getInstrInfo();
235 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000236 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
237
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000238 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000239 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000240 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000241
242 HasFarJump = false;
243
Evan Chenga8e29892007-01-19 07:51:42 +0000244 // Renumber all of the machine basic blocks in the function, guaranteeing that
245 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000246 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000247
Evan Chengd26b14c2009-07-31 18:28:05 +0000248 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000249 // This is so we can keep exact track of where the alignment padding goes.
250
Evan Chengd26b14c2009-07-31 18:28:05 +0000251 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000252 // aligned.
253 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000254
Evan Chenga8e29892007-01-19 07:51:42 +0000255 // Perform the initial placement of the constant pool entries. To start with,
256 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000257 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000258 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000259 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000260 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000261 AFI->setAlign(2U);
262 }
Bob Wilson84945262009-05-12 17:09:30 +0000263
Evan Chenga8e29892007-01-19 07:51:42 +0000264 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000265 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000266
Evan Chenga8e29892007-01-19 07:51:42 +0000267 // Do the initial scan of the function, building up information about the
268 // sizes of each block, the location of all the water, and finding all of the
269 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000270 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000271 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000272
Evan Chenged884f32007-04-03 23:39:48 +0000273 /// Remove dead constant pool entries.
274 RemoveUnusedCPEntries();
275
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000276 // Iteratively place constant pool entries and fix up branches until there
277 // is no change.
278 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000279 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000280 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000281 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000282 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000283 CPChange |= HandleConstantPoolUser(MF, i);
284 if (CPChange && ++NoCPIters > 30)
285 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000286 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000287
288 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000289 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000290 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
291 if (BRChange && ++NoBRIters > 30)
292 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000293 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000294
295 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000296 break;
297 MadeChange = true;
298 }
Evan Chenged884f32007-04-03 23:39:48 +0000299
Evan Chenga1efbbd2009-08-14 00:32:16 +0000300 // Shrink 32-bit Thumb2 branch, load, and store instructions.
301 if (isThumb2)
302 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000303
Dale Johannesen8593e412007-04-29 19:19:30 +0000304 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000305 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000306
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000307 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
308 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000309 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000310 MadeChange |= UndoLRSpillRestore();
311
Evan Chenga8e29892007-01-19 07:51:42 +0000312 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000313 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000314 WaterList.clear();
315 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000316 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000317 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000318 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000319 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000320
321 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000322}
323
324/// DoInitialPlacement - Perform the initial placement of the constant pool
325/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000326void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000327 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000328 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000329 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
330 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000331
Evan Chenga8e29892007-01-19 07:51:42 +0000332 // Add all of the constants from the constant pool to the end block, use an
333 // identity mapping of CPI's to CPE's.
334 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000335 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000336
Evan Cheng5657c012009-07-29 02:18:14 +0000337 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000338 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000339 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000340 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
341 // we would have to pad them out or something so that instructions stay
342 // aligned.
343 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
344 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000345 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000346 .addImm(i).addConstantPoolIndex(i).addImm(Size);
347 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000348
349 // Add a new CPEntry, but no corresponding CPUser yet.
350 std::vector<CPEntry> CPEs;
351 CPEs.push_back(CPEntry(CPEMI, i));
352 CPEntries.push_back(CPEs);
353 NumCPEs++;
354 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000355 }
356}
357
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000358/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000359/// into the block immediately after it.
360static bool BBHasFallthrough(MachineBasicBlock *MBB) {
361 // Get the next machine basic block in the function.
362 MachineFunction::iterator MBBI = MBB;
363 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
364 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000365
Evan Chenga8e29892007-01-19 07:51:42 +0000366 MachineBasicBlock *NextBB = next(MBBI);
367 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
368 E = MBB->succ_end(); I != E; ++I)
369 if (*I == NextBB)
370 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000371
Evan Chenga8e29892007-01-19 07:51:42 +0000372 return false;
373}
374
Evan Chengc99ef082007-02-09 20:54:44 +0000375/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
376/// look up the corresponding CPEntry.
377ARMConstantIslands::CPEntry
378*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
379 const MachineInstr *CPEMI) {
380 std::vector<CPEntry> &CPEs = CPEntries[CPI];
381 // Number of entries per constpool index should be small, just do a
382 // linear search.
383 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
384 if (CPEs[i].CPEMI == CPEMI)
385 return &CPEs[i];
386 }
387 return NULL;
388}
389
Evan Chenga8e29892007-01-19 07:51:42 +0000390/// InitialFunctionScan - Do the initial scan of the function, building up
391/// information about the sizes of each block, the location of all the water,
392/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000393void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000394 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000395 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000396 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000397 MBBI != E; ++MBBI) {
398 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000399
Evan Chenga8e29892007-01-19 07:51:42 +0000400 // If this block doesn't fall through into the next MBB, then this is
401 // 'water' that a constant pool island could be placed.
402 if (!BBHasFallthrough(&MBB))
403 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000404
Evan Chenga8e29892007-01-19 07:51:42 +0000405 unsigned MBBSize = 0;
406 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
407 I != E; ++I) {
408 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000409 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000410
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000411 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000412 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000413 bool isCond = false;
414 unsigned Bits = 0;
415 unsigned Scale = 1;
416 int UOpc = Opc;
417 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000418 default:
419 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000420 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000421 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000422 // be right, functions containing these must be 4-byte aligned.
423 AFI->setAlign(2U);
424 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000425 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000426 MBBSize += 2; // padding
427 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000428 case ARM::t2BR_JT:
429 T2JumpTables.push_back(I);
430 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000431 case ARM::Bcc:
432 isCond = true;
433 UOpc = ARM::B;
434 // Fallthrough
435 case ARM::B:
436 Bits = 24;
437 Scale = 4;
438 break;
439 case ARM::tBcc:
440 isCond = true;
441 UOpc = ARM::tB;
442 Bits = 8;
443 Scale = 2;
444 break;
445 case ARM::tB:
446 Bits = 11;
447 Scale = 2;
448 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000449 case ARM::t2Bcc:
450 isCond = true;
451 UOpc = ARM::t2B;
452 Bits = 20;
453 Scale = 2;
454 break;
455 case ARM::t2B:
456 Bits = 24;
457 Scale = 2;
458 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000459 }
Evan Chengb43216e2007-02-01 10:16:15 +0000460
461 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000462 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000463 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000464 }
465
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000466 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
467 PushPopMIs.push_back(I);
468
Evan Chengd3d9d662009-07-23 18:27:47 +0000469 if (Opc == ARM::CONSTPOOL_ENTRY)
470 continue;
471
Evan Chenga8e29892007-01-19 07:51:42 +0000472 // Scan the instructions for constant pool operands.
473 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000474 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000475 // We found one. The addressing mode tells us the max displacement
476 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000477
Evan Chenga8e29892007-01-19 07:51:42 +0000478 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000479 unsigned Bits = 0;
480 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000481 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000482 bool IsSoImm = false;
483
484 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000485 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000486 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000487 break;
488
489 // Taking the address of a CP entry.
490 case ARM::LEApcrel:
491 // This takes a SoImm, which is 8 bit immediate rotated. We'll
492 // pretend the maximum offset is 255 * 4. Since each instruction
493 // 4 byte wide, this is always correct. We'llc heck for other
494 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000495 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000496 Scale = 4;
497 NegOk = true;
498 IsSoImm = true;
499 break;
500 case ARM::t2LEApcrel:
501 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000502 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000503 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000504 case ARM::tLEApcrel:
505 Bits = 8;
506 Scale = 4;
507 break;
508
509 case ARM::LDR:
510 case ARM::LDRcp:
511 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000512 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000513 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000514 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000515
516 case ARM::tLDRpci:
517 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000518 Bits = 8;
519 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000520 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000521
522 case ARM::FLDD:
523 case ARM::FLDS:
524 Bits = 8;
525 Scale = 4; // +-(offset_8*4)
526 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000527 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000528 }
Evan Chengb43216e2007-02-01 10:16:15 +0000529
Evan Chenga8e29892007-01-19 07:51:42 +0000530 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000531 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000532 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000533 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000534 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000535
536 // Increment corresponding CPEntry reference count.
537 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
538 assert(CPE && "Cannot find a corresponding CPEntry!");
539 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000540
Evan Chenga8e29892007-01-19 07:51:42 +0000541 // Instructions can only use one CP entry, don't bother scanning the
542 // rest of the operands.
543 break;
544 }
545 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000546
Dale Johannesen8593e412007-04-29 19:19:30 +0000547 // In thumb mode, if this block is a constpool island, we may need padding
548 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000549 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000550 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000551 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
552 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000553 MBBSize += 2;
554
Evan Chenga8e29892007-01-19 07:51:42 +0000555 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000556 BBOffsets.push_back(Offset);
557 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000558 }
559}
560
Evan Chenga8e29892007-01-19 07:51:42 +0000561/// GetOffsetOf - Return the current offset of the specified machine instruction
562/// from the start of the function. This offset changes as stuff is moved
563/// around inside the function.
564unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
565 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000566
Evan Chenga8e29892007-01-19 07:51:42 +0000567 // The offset is composed of two things: the sum of the sizes of all MBB's
568 // before this instruction's block, and the offset from the start of the block
569 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000570 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000571
Dale Johannesen8593e412007-04-29 19:19:30 +0000572 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
573 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000574 if (isThumb &&
575 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000576 Offset%4 != 0)
577 Offset += 2;
578
Evan Chenga8e29892007-01-19 07:51:42 +0000579 // Sum instructions before MI in MBB.
580 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
581 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
582 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000583 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000584 }
585}
586
587/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
588/// ID.
589static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
590 const MachineBasicBlock *RHS) {
591 return LHS->getNumber() < RHS->getNumber();
592}
593
594/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
595/// machine function, it upsets all of the block numbers. Renumber the blocks
596/// and update the arrays that parallel this numbering.
597void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
598 // Renumber the MBB's to keep them consequtive.
599 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000600
Evan Chenga8e29892007-01-19 07:51:42 +0000601 // Insert a size into BBSizes to align it properly with the (newly
602 // renumbered) block numbers.
603 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000604
605 // Likewise for BBOffsets.
606 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000607
608 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000609 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000610 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000611 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
612 CompareMBBNumbers);
613 WaterList.insert(IP, NewBB);
614}
615
616
617/// Split the basic block containing MI into two blocks, which are joined by
618/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000619/// account for this change and returns the newly created block.
620MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000621 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000622 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000623
624 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000625 MachineBasicBlock *NewBB =
626 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000627 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000628 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000629
Evan Chenga8e29892007-01-19 07:51:42 +0000630 // Splice the instructions starting with MI over to NewBB.
631 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000632
Evan Chenga8e29892007-01-19 07:51:42 +0000633 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000634 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000635 // There doesn't seem to be meaningful DebugInfo available; this doesn't
636 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000637 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
638 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000639 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000640
Evan Chenga8e29892007-01-19 07:51:42 +0000641 // Update the CFG. All succs of OrigBB are now succs of NewBB.
642 while (!OrigBB->succ_empty()) {
643 MachineBasicBlock *Succ = *OrigBB->succ_begin();
644 OrigBB->removeSuccessor(Succ);
645 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000646
Evan Chenga8e29892007-01-19 07:51:42 +0000647 // This pass should be run after register allocation, so there should be no
648 // PHI nodes to update.
649 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
650 && "PHI nodes should be eliminated by now!");
651 }
Bob Wilson84945262009-05-12 17:09:30 +0000652
Evan Chenga8e29892007-01-19 07:51:42 +0000653 // OrigBB branches to NewBB.
654 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000655
Evan Chenga8e29892007-01-19 07:51:42 +0000656 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000657 // This is almost the same as UpdateForInsertedWaterBlock, except that
658 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000659 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000660
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000661 // Insert a size into BBSizes to align it properly with the (newly
662 // renumbered) block numbers.
663 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000664
Dale Johannesen99c49a42007-02-25 00:47:03 +0000665 // Likewise for BBOffsets.
666 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
667
Bob Wilson84945262009-05-12 17:09:30 +0000668 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000669 // available water after it (but not if it's already there, which happens
670 // when splitting before a conditional branch that is followed by an
671 // unconditional branch - in that case we want to insert NewBB).
672 std::vector<MachineBasicBlock*>::iterator IP =
673 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
674 CompareMBBNumbers);
675 MachineBasicBlock* WaterBB = *IP;
676 if (WaterBB == OrigBB)
677 WaterList.insert(next(IP), NewBB);
678 else
679 WaterList.insert(IP, OrigBB);
680
Dale Johannesen8593e412007-04-29 19:19:30 +0000681 // Figure out how large the first NewMBB is. (It cannot
682 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000683 unsigned NewBBSize = 0;
684 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
685 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000686 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000687
Dale Johannesen99c49a42007-02-25 00:47:03 +0000688 unsigned OrigBBI = OrigBB->getNumber();
689 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000690 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000691 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000692
Evan Chenga8e29892007-01-19 07:51:42 +0000693 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000694 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000695 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000696 BBSizes[OrigBBI] -= NewBBSize - delta;
697
698 // ...and adjust BBOffsets for NewBB accordingly.
699 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
700
701 // All BBOffsets following these blocks must be modified.
702 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000703
704 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000705}
706
Dale Johannesen8593e412007-04-29 19:19:30 +0000707/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000708/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000709/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000710bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000711 unsigned TrialOffset, unsigned MaxDisp,
712 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000713 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
714 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000715 // Effectively, the valid range of displacements is 2 bytes smaller for such
716 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000717 unsigned TotalAdj = 0;
718 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000719 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000720 TotalAdj = 2;
721 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000722 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000723 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000724 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000725 TotalAdj += 2;
726 }
727
728 // In Thumb2 mode, later branch adjustments can shift instructions up and
729 // cause alignment change. In the worst case scenario this can cause the
730 // user's effective address to be subtracted by 2 and the CPE's address to
731 // be plus 2.
732 if (isThumb2 && TotalAdj != 4)
733 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000734
Dale Johannesen99c49a42007-02-25 00:47:03 +0000735 if (UserOffset <= TrialOffset) {
736 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000737 if (TrialOffset - UserOffset <= MaxDisp)
738 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000739 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000740 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000741 if (UserOffset - TrialOffset <= MaxDisp)
742 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000743 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000744 }
745 return false;
746}
747
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000748/// WaterIsInRange - Returns true if a CPE placed after the specified
749/// Water (a basic block) will be in range for the specific MI.
750
751bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000752 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000753 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000754 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000755 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000756
Dale Johannesend959aa42007-04-02 20:31:06 +0000757 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000758 // the offset of the instruction. (Currently applies only to ARM, so
759 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000760 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000761 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000762
Evan Chengd3d9d662009-07-23 18:27:47 +0000763 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000764}
765
766/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000767/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000768bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000769 MachineInstr *CPEMI, unsigned MaxDisp,
770 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000771 unsigned CPEOffset = GetOffsetOf(CPEMI);
772 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000773
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000774 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000775 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
776 << " max delta=" << MaxDisp
777 << " insn address=" << UserOffset
778 << " CPE address=" << CPEOffset
779 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000780 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000781
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000782 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000783}
784
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000785#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000786/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
787/// unconditionally branches to its only successor.
788static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
789 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
790 return false;
791
792 MachineBasicBlock *Succ = *MBB->succ_begin();
793 MachineBasicBlock *Pred = *MBB->pred_begin();
794 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000795 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
796 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000797 return PredMI->getOperand(0).getMBB() == Succ;
798 return false;
799}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000800#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000801
Bob Wilson84945262009-05-12 17:09:30 +0000802void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000803 int delta) {
804 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000805 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
806 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000807 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000808 // If some existing blocks have padding, adjust the padding as needed, a
809 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000810 if (!isThumb)
811 continue;
812 MachineBasicBlock *MBB = MBBI;
813 if (!MBB->empty()) {
814 // Constant pool entries require padding.
815 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000816 unsigned OldOffset = BBOffsets[i] - delta;
817 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000818 // add new padding
819 BBSizes[i] += 2;
820 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000821 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000822 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000823 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000824 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000825 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000826 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000827 // Thumb1 jump tables require padding. They should be at the end;
828 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000829 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000830 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000831 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
832 unsigned OldMIOffset = NewMIOffset - delta;
833 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000834 // remove existing padding
835 BBSizes[i] -= 2;
836 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000837 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000838 // add new padding
839 BBSizes[i] += 2;
840 delta += 2;
841 }
842 }
843 if (delta==0)
844 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000845 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000846 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000847 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000848}
849
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000850/// DecrementOldEntry - find the constant pool entry with index CPI
851/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000852/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000853/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000854
Evan Chenged884f32007-04-03 23:39:48 +0000855bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000856 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000857 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
858 assert(CPE && "Unexpected!");
859 if (--CPE->RefCount == 0) {
860 RemoveDeadCPEMI(CPEMI);
861 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000862 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000863 return true;
864 }
865 return false;
866}
867
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000868/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
869/// if not, see if an in-range clone of the CPE is in range, and if so,
870/// change the data structures so the user references the clone. Returns:
871/// 0 = no existing entry found
872/// 1 = entry found, and there were no code insertions or deletions
873/// 2 = entry found, and there were code insertions or deletions
874int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
875{
876 MachineInstr *UserMI = U.MI;
877 MachineInstr *CPEMI = U.CPEMI;
878
879 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000880 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000881 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000882 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000883 }
884
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000885 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000886 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000887 std::vector<CPEntry> &CPEs = CPEntries[CPI];
888 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
889 // We already tried this one
890 if (CPEs[i].CPEMI == CPEMI)
891 continue;
892 // Removing CPEs can leave empty entries, skip
893 if (CPEs[i].CPEMI == NULL)
894 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000895 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000896 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
897 // Point the CPUser node to the replacement
898 U.CPEMI = CPEs[i].CPEMI;
899 // Change the CPI in the instruction operand to refer to the clone.
900 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000901 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000902 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903 break;
904 }
905 // Adjust the refcount of the clone...
906 CPEs[i].RefCount++;
907 // ...and the original. If we didn't remove the old entry, none of the
908 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000909 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000910 }
911 }
912 return 0;
913}
914
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000915/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
916/// the specific unconditional branch instruction.
917static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000918 switch (Opc) {
919 case ARM::tB:
920 return ((1<<10)-1)*2;
921 case ARM::t2B:
922 return ((1<<23)-1)*2;
923 default:
924 break;
925 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000926
David Goodwin5e47a9a2009-06-30 18:04:13 +0000927 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000928}
929
Dale Johannesen8593e412007-04-29 19:19:30 +0000930/// AcceptWater - Small amount of common code factored out of the following.
931
Bob Wilson84945262009-05-12 17:09:30 +0000932MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000933 std::vector<MachineBasicBlock*>::iterator IP) {
934 DOUT << "found water in range\n";
935 // Remove the original WaterList entry; we want subsequent
936 // insertions in this vicinity to go after the one we're
937 // about to insert. This considerably reduces the number
938 // of times we have to move the same CPE more than once.
939 WaterList.erase(IP);
940 // CPE goes before following block (NewMBB).
941 return next(MachineFunction::iterator(WaterBB));
942}
943
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000944/// LookForWater - look for an existing entry in the WaterList in which
945/// we can place the CPE referenced from U so it's within range of U's MI.
946/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000947/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000948/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000949/// water that will not introduce padding to water that will; within each
950/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000951bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000952 MachineBasicBlock** NewMBB) {
953 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
954 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000955 if (!WaterList.empty()) {
956 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000957 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000958 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000959 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000960 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000961 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000962 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000963 // This is valid Water, but would introduce padding. Remember
964 // it in case we don't find any Water that doesn't do this.
965 if (!WaterBBThatWouldPad) {
966 WaterBBThatWouldPad = WaterBB;
967 IPThatWouldPad = IP;
968 }
969 } else {
970 *NewMBB = AcceptWater(WaterBB, IP);
971 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000972 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000973 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000974 if (IP == B)
975 break;
976 }
977 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000978 if (isThumb && WaterBBThatWouldPad) {
979 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
980 return true;
981 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000982 return false;
983}
984
Bob Wilson84945262009-05-12 17:09:30 +0000985/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000986/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
987/// block is used if in range, and the conditional branch munged so control
988/// flow is correct. Otherwise the block is split to create a hole with an
989/// unconditional branch around it. In either case *NewMBB is set to a
990/// block following which the new island can be inserted (the WaterList
991/// is not adjusted).
992
Bob Wilson84945262009-05-12 17:09:30 +0000993void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000994 unsigned UserOffset, MachineBasicBlock** NewMBB) {
995 CPUser &U = CPUsers[CPUserIndex];
996 MachineInstr *UserMI = U.MI;
997 MachineInstr *CPEMI = U.CPEMI;
998 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000999 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001000 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001001 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001002
1003 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +00001004 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-07-23 18:27:47 +00001005 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
1006 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001007 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +00001008 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +00001009 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001010 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +00001011 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1012 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001013 DOUT << "Split at end of block\n";
1014 if (&UserMBB->back() == UserMI)
1015 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1016 *NewMBB = next(MachineFunction::iterator(UserMBB));
1017 // Add an unconditional branch from UserMBB to fallthrough block.
1018 // Record it for branch lengthening; this new branch will not get out of
1019 // range, but if the preceding conditional branch is out of range, the
1020 // targets will be exchanged, and the altered branch may be out of
1021 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001022 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001023 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1024 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001025 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001026 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001027 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001028 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001029 BBSizes[UserMBB->getNumber()] += delta;
1030 AdjustBBOffsetsAfter(UserMBB, delta);
1031 } else {
1032 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001033 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001034 // and constant pool entries are 4 bytes: if instruction I references
1035 // island CPE, and instruction I+1 references CPE', it will
1036 // not work well to put CPE as far forward as possible, since then
1037 // CPE' cannot immediately follow it (that location is 2 bytes
1038 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001039 // a new island. So, we make a first guess, then walk through the
1040 // instructions between the one currently being looked at and the
1041 // possible insertion point, and make sure any other instructions
1042 // that reference CPEs will be able to use the same island area;
1043 // if not, we back up the insertion point.
1044
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001045 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001046 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001047 // island is handled inside OffsetIsInRange.
1048 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001049 // This could point off the end of the block if we've already got
1050 // constant pool entries following this block; only the last one is
1051 // in the water list. Back past any possible branches (allow for a
1052 // conditional and a maximally long unconditional).
1053 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001054 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001055 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001056 unsigned EndInsertOffset = BaseInsertOffset +
1057 CPEMI->getOperand(2).getImm();
1058 MachineBasicBlock::iterator MI = UserMI;
1059 ++MI;
1060 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001061 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001062 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001063 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001064 MI = next(MI)) {
1065 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001066 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001067 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001068 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1069 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1070 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001071 }
1072 // This is overly conservative, as we don't account for CPEMIs
1073 // being reused within the block, but it doesn't matter much.
1074 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1075 CPUIndex++;
1076 }
1077 }
1078 DOUT << "Split in middle of big block\n";
1079 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1080 }
1081}
1082
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001083/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001084/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001085/// place in-range. Return true if we changed any addresses (thus must run
1086/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001087bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001088 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001089 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001090 MachineInstr *UserMI = U.MI;
1091 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001092 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001093 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001094 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001095 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001096 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001097 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001098
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099 // See if the current entry is within range, or there is a clone of it
1100 // in range.
1101 int result = LookForExistingCPEntry(U, UserOffset);
1102 if (result==1) return false;
1103 else if (result==2) return true;
1104
1105 // No existing clone of this CPE is within range.
1106 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001107 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001108
1109 // Look for water where we can place this CPE. We look for the farthest one
1110 // away that will work. Forward references only for now (although later
1111 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001112
Dale Johannesen8593e412007-04-29 19:19:30 +00001113 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001114 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001115 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001116 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001117 }
1118
1119 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001120 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1121 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001122
1123 // Update internal data structures to account for the newly inserted MBB.
1124 UpdateForInsertedWaterBlock(NewIsland);
1125
1126 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001127 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001128
1129 // Now that we have an island to add the CPE to, clone the original CPE and
1130 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001131 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1132 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001133 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001134 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001135 NumCPEs++;
1136
Dale Johannesen8593e412007-04-29 19:19:30 +00001137 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001138 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001139 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001140 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001141 // Increase the size of the island block to account for the new entry.
1142 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001143 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001144
Evan Chenga8e29892007-01-19 07:51:42 +00001145 // Finally, change the CPI in the instruction operand to be ID.
1146 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001147 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001148 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001149 break;
1150 }
Bob Wilson84945262009-05-12 17:09:30 +00001151
Chris Lattner705e07f2009-08-23 03:41:05 +00001152 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1153 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001154
Evan Chenga8e29892007-01-19 07:51:42 +00001155 return true;
1156}
1157
Evan Chenged884f32007-04-03 23:39:48 +00001158/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1159/// sizes and offsets of impacted basic blocks.
1160void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1161 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001162 unsigned Size = CPEMI->getOperand(2).getImm();
1163 CPEMI->eraseFromParent();
1164 BBSizes[CPEBB->getNumber()] -= Size;
1165 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001166 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001167 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001168 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001169 // empty, so fix this.
1170 // All succeeding offsets have the current size value added in, fix this.
1171 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001172 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001173 BBSizes[CPEBB->getNumber()] = 0;
1174 }
Evan Chenged884f32007-04-03 23:39:48 +00001175 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001176 AdjustBBOffsetsAfter(CPEBB, -Size);
1177 // An island has only one predecessor BB and one successor BB. Check if
1178 // this BB's predecessor jumps directly to this BB's successor. This
1179 // shouldn't happen currently.
1180 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1181 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001182}
1183
1184/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1185/// are zero.
1186bool ARMConstantIslands::RemoveUnusedCPEntries() {
1187 unsigned MadeChange = false;
1188 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1189 std::vector<CPEntry> &CPEs = CPEntries[i];
1190 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1191 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1192 RemoveDeadCPEMI(CPEs[j].CPEMI);
1193 CPEs[j].CPEMI = NULL;
1194 MadeChange = true;
1195 }
1196 }
Bob Wilson84945262009-05-12 17:09:30 +00001197 }
Evan Chenged884f32007-04-03 23:39:48 +00001198 return MadeChange;
1199}
1200
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001201/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001202/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001203bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1204 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001205 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001206 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001207 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001208
Chris Lattner705e07f2009-08-23 03:41:05 +00001209 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1210 << " from BB#" << MI->getParent()->getNumber()
1211 << " max delta=" << MaxDisp
1212 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1213 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001214
Dale Johannesen8593e412007-04-29 19:19:30 +00001215 if (BrOffset <= DestOffset) {
1216 // Branch before the Dest.
1217 if (DestOffset-BrOffset <= MaxDisp)
1218 return true;
1219 } else {
1220 if (BrOffset-DestOffset <= MaxDisp)
1221 return true;
1222 }
1223 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001224}
1225
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001226/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1227/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001228bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001229 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001230 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001231
Evan Chengc0dbec72007-01-31 19:57:44 +00001232 // Check to see if the DestBB is already in-range.
1233 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001234 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001235
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001236 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001237 return FixUpUnconditionalBr(MF, Br);
1238 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001239}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001240
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001241/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1242/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001243/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001244/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001245bool
Evan Cheng5657c012009-07-29 02:18:14 +00001246ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001247 MachineInstr *MI = Br.MI;
1248 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001249 if (!isThumb1)
1250 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001251
1252 // Use BL to implement far jump.
1253 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001254 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001255 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001256 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001257 HasFarJump = true;
1258 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001259
Chris Lattner705e07f2009-08-23 03:41:05 +00001260 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001261
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001262 return true;
1263}
1264
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001265/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001266/// far away to fit in its displacement field. It is converted to an inverse
1267/// conditional branch + an unconditional branch to the destination.
1268bool
Evan Cheng5657c012009-07-29 02:18:14 +00001269ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001270 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001271 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001272
Bob Wilson39bf0512009-05-12 17:35:29 +00001273 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001274 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001275 // blt L1
1276 // =>
1277 // bge L2
1278 // b L1
1279 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001280 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001281 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001282 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001283
1284 // If the branch is at the end of its MBB and that has a fall-through block,
1285 // direct the updated conditional branch to the fall-through block. Otherwise,
1286 // split the MBB before the next instruction.
1287 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001288 MachineInstr *BMI = &MBB->back();
1289 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001290
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001291 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001292 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001293 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001294 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001295 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001296 // condition and swap destinations:
1297 // beq L1
1298 // b L2
1299 // =>
1300 // bne L2
1301 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001302 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001303 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001304 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1305 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001306 BMI->getOperand(0).setMBB(DestBB);
1307 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001308 MI->getOperand(1).setImm(CC);
1309 return true;
1310 }
1311 }
1312 }
1313
1314 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001315 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001316 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001317 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001318 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001319 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001320 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1321 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001322 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001323 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001324 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001325 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001326
Evan Chengc99ef082007-02-09 20:54:44 +00001327 DOUT << " Insert B to BB#" << DestBB->getNumber()
1328 << " also invert condition and change dest. to BB#"
1329 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001330
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001331 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001332 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001333 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1334 TII->get(MI->getOpcode()))
1335 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001336 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001337 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001338 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001339 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001340 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001341 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001342
1343 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001344 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001345 MI->eraseFromParent();
1346
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001347 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001348 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001349 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001350 return true;
1351}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001352
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001353/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001354/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1355/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001356bool ARMConstantIslands::UndoLRSpillRestore() {
1357 bool MadeChange = false;
1358 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1359 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001360 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng48bd7e32009-08-13 06:05:07 +00001361 MI->getOperand(2).getReg() == ARM::PC &&
1362 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001363 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001364 MI->eraseFromParent();
1365 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001366 }
1367 }
1368 return MadeChange;
1369}
Evan Cheng5657c012009-07-29 02:18:14 +00001370
Evan Chenga1efbbd2009-08-14 00:32:16 +00001371bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1372 bool MadeChange = false;
1373
1374 // Shrink ADR and LDR from constantpool.
1375 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1376 CPUser &U = CPUsers[i];
1377 unsigned Opcode = U.MI->getOpcode();
1378 unsigned NewOpc = 0;
1379 unsigned Scale = 1;
1380 unsigned Bits = 0;
1381 switch (Opcode) {
1382 default: break;
1383 case ARM::t2LEApcrel:
1384 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1385 NewOpc = ARM::tLEApcrel;
1386 Bits = 8;
1387 Scale = 4;
1388 }
1389 break;
1390 case ARM::t2LDRpci:
1391 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1392 NewOpc = ARM::tLDRpci;
1393 Bits = 8;
1394 Scale = 4;
1395 }
1396 break;
1397 }
1398
1399 if (!NewOpc)
1400 continue;
1401
1402 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1403 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1404 // FIXME: Check if offset is multiple of scale if scale is not 4.
1405 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1406 U.MI->setDesc(TII->get(NewOpc));
1407 MachineBasicBlock *MBB = U.MI->getParent();
1408 BBSizes[MBB->getNumber()] -= 2;
1409 AdjustBBOffsetsAfter(MBB, -2);
1410 ++NumT2CPShrunk;
1411 MadeChange = true;
1412 }
1413 }
1414
Evan Chenga1efbbd2009-08-14 00:32:16 +00001415 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001416 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001417 return MadeChange;
1418}
1419
1420bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001421 bool MadeChange = false;
1422
1423 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1424 ImmBranch &Br = ImmBranches[i];
1425 unsigned Opcode = Br.MI->getOpcode();
1426 unsigned NewOpc = 0;
1427 unsigned Scale = 1;
1428 unsigned Bits = 0;
1429 switch (Opcode) {
1430 default: break;
1431 case ARM::t2B:
1432 NewOpc = ARM::tB;
1433 Bits = 11;
1434 Scale = 2;
1435 break;
1436 case ARM::t2Bcc:
1437 NewOpc = ARM::tBcc;
1438 Bits = 8;
1439 Scale = 2;
1440 break;
1441 }
1442 if (!NewOpc)
1443 continue;
1444
1445 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1446 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1447 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1448 Br.MI->setDesc(TII->get(NewOpc));
1449 MachineBasicBlock *MBB = Br.MI->getParent();
1450 BBSizes[MBB->getNumber()] -= 2;
1451 AdjustBBOffsetsAfter(MBB, -2);
1452 ++NumT2BrShrunk;
1453 MadeChange = true;
1454 }
1455 }
1456
1457 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001458}
1459
1460
1461/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1462/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001463bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1464 bool MadeChange = false;
1465
1466 // FIXME: After the tables are shrunk, can we get rid some of the
1467 // constantpool tables?
1468 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1469 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1470 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1471 MachineInstr *MI = T2JumpTables[i];
1472 const TargetInstrDesc &TID = MI->getDesc();
1473 unsigned NumOps = TID.getNumOperands();
1474 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1475 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1476 unsigned JTI = JTOP.getIndex();
1477 assert(JTI < JT.size());
1478
1479 bool ByteOk = true;
1480 bool HalfWordOk = true;
1481 unsigned JTOffset = GetOffsetOf(MI) + 4;
1482 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1483 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1484 MachineBasicBlock *MBB = JTBBs[j];
1485 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001486 // Negative offset is not ok. FIXME: We should change BB layout to make
1487 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001488 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001489 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001490 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001491 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001492 HalfWordOk = false;
1493 if (!ByteOk && !HalfWordOk)
1494 break;
1495 }
1496
1497 if (ByteOk || HalfWordOk) {
1498 MachineBasicBlock *MBB = MI->getParent();
1499 unsigned BaseReg = MI->getOperand(0).getReg();
1500 bool BaseRegKill = MI->getOperand(0).isKill();
1501 if (!BaseRegKill)
1502 continue;
1503 unsigned IdxReg = MI->getOperand(1).getReg();
1504 bool IdxRegKill = MI->getOperand(1).isKill();
1505 MachineBasicBlock::iterator PrevI = MI;
1506 if (PrevI == MBB->begin())
1507 continue;
1508
1509 MachineInstr *AddrMI = --PrevI;
1510 bool OptOk = true;
1511 // Examine the instruction that calculate the jumptable entry address.
1512 // If it's not the one just before the t2BR_JT, we won't delete it, then
1513 // it's not worth doing the optimization.
1514 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1515 const MachineOperand &MO = AddrMI->getOperand(k);
1516 if (!MO.isReg() || !MO.getReg())
1517 continue;
1518 if (MO.isDef() && MO.getReg() != BaseReg) {
1519 OptOk = false;
1520 break;
1521 }
1522 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1523 OptOk = false;
1524 break;
1525 }
1526 }
1527 if (!OptOk)
1528 continue;
1529
Evan Chenga1efbbd2009-08-14 00:32:16 +00001530 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1531 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001532 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001533 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1534 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001535 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001536 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001537
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001538 if (!OptOk)
1539 continue;
1540
1541 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1542 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1543 .addReg(IdxReg, getKillRegState(IdxRegKill))
1544 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1545 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1546 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1547 // is 2-byte aligned. For now, asm printer will fix it up.
1548 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1549 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1550 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1551 OrigSize += TII->GetInstSizeInBytes(MI);
1552
1553 AddrMI->eraseFromParent();
1554 LeaMI->eraseFromParent();
1555 MI->eraseFromParent();
1556
1557 int delta = OrigSize - NewSize;
1558 BBSizes[MBB->getNumber()] -= delta;
1559 AdjustBBOffsetsAfter(MBB, -delta);
1560
1561 ++NumTBs;
1562 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001563 }
1564 }
1565
1566 return MadeChange;
1567}