blob: 43a823daee07fb861ced5cdfd3c01e1f917fcafa [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) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000220 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
221 << " 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++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000354 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
355 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000356 }
357}
358
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000359/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000360/// into the block immediately after it.
361static bool BBHasFallthrough(MachineBasicBlock *MBB) {
362 // Get the next machine basic block in the function.
363 MachineFunction::iterator MBBI = MBB;
364 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
365 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000366
Evan Chenga8e29892007-01-19 07:51:42 +0000367 MachineBasicBlock *NextBB = next(MBBI);
368 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
369 E = MBB->succ_end(); I != E; ++I)
370 if (*I == NextBB)
371 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000372
Evan Chenga8e29892007-01-19 07:51:42 +0000373 return false;
374}
375
Evan Chengc99ef082007-02-09 20:54:44 +0000376/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
377/// look up the corresponding CPEntry.
378ARMConstantIslands::CPEntry
379*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
380 const MachineInstr *CPEMI) {
381 std::vector<CPEntry> &CPEs = CPEntries[CPI];
382 // Number of entries per constpool index should be small, just do a
383 // linear search.
384 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
385 if (CPEs[i].CPEMI == CPEMI)
386 return &CPEs[i];
387 }
388 return NULL;
389}
390
Evan Chenga8e29892007-01-19 07:51:42 +0000391/// InitialFunctionScan - Do the initial scan of the function, building up
392/// information about the sizes of each block, the location of all the water,
393/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000394void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000395 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000396 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000397 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000398 MBBI != E; ++MBBI) {
399 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000400
Evan Chenga8e29892007-01-19 07:51:42 +0000401 // If this block doesn't fall through into the next MBB, then this is
402 // 'water' that a constant pool island could be placed.
403 if (!BBHasFallthrough(&MBB))
404 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000405
Evan Chenga8e29892007-01-19 07:51:42 +0000406 unsigned MBBSize = 0;
407 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
408 I != E; ++I) {
409 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000410 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000411
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000412 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000413 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000414 bool isCond = false;
415 unsigned Bits = 0;
416 unsigned Scale = 1;
417 int UOpc = Opc;
418 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000419 default:
420 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000421 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000422 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000423 // be right, functions containing these must be 4-byte aligned.
424 AFI->setAlign(2U);
425 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000426 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000427 MBBSize += 2; // padding
428 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000429 case ARM::t2BR_JT:
430 T2JumpTables.push_back(I);
431 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000432 case ARM::Bcc:
433 isCond = true;
434 UOpc = ARM::B;
435 // Fallthrough
436 case ARM::B:
437 Bits = 24;
438 Scale = 4;
439 break;
440 case ARM::tBcc:
441 isCond = true;
442 UOpc = ARM::tB;
443 Bits = 8;
444 Scale = 2;
445 break;
446 case ARM::tB:
447 Bits = 11;
448 Scale = 2;
449 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000450 case ARM::t2Bcc:
451 isCond = true;
452 UOpc = ARM::t2B;
453 Bits = 20;
454 Scale = 2;
455 break;
456 case ARM::t2B:
457 Bits = 24;
458 Scale = 2;
459 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000460 }
Evan Chengb43216e2007-02-01 10:16:15 +0000461
462 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000463 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000464 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000465 }
466
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000467 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
468 PushPopMIs.push_back(I);
469
Evan Chengd3d9d662009-07-23 18:27:47 +0000470 if (Opc == ARM::CONSTPOOL_ENTRY)
471 continue;
472
Evan Chenga8e29892007-01-19 07:51:42 +0000473 // Scan the instructions for constant pool operands.
474 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000475 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000476 // We found one. The addressing mode tells us the max displacement
477 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000478
Evan Chenga8e29892007-01-19 07:51:42 +0000479 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000480 unsigned Bits = 0;
481 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000482 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000483 bool IsSoImm = false;
484
485 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000486 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000487 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000488 break;
489
490 // Taking the address of a CP entry.
491 case ARM::LEApcrel:
492 // This takes a SoImm, which is 8 bit immediate rotated. We'll
493 // pretend the maximum offset is 255 * 4. Since each instruction
494 // 4 byte wide, this is always correct. We'llc heck for other
495 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000496 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000497 Scale = 4;
498 NegOk = true;
499 IsSoImm = true;
500 break;
501 case ARM::t2LEApcrel:
502 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000503 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000504 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000505 case ARM::tLEApcrel:
506 Bits = 8;
507 Scale = 4;
508 break;
509
510 case ARM::LDR:
511 case ARM::LDRcp:
512 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000513 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000514 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000515 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000516
517 case ARM::tLDRpci:
518 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000519 Bits = 8;
520 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000521 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000522
523 case ARM::FLDD:
524 case ARM::FLDS:
525 Bits = 8;
526 Scale = 4; // +-(offset_8*4)
527 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000528 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000529 }
Evan Chengb43216e2007-02-01 10:16:15 +0000530
Evan Chenga8e29892007-01-19 07:51:42 +0000531 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000532 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000533 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000534 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000535 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000536
537 // Increment corresponding CPEntry reference count.
538 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
539 assert(CPE && "Cannot find a corresponding CPEntry!");
540 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000541
Evan Chenga8e29892007-01-19 07:51:42 +0000542 // Instructions can only use one CP entry, don't bother scanning the
543 // rest of the operands.
544 break;
545 }
546 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000547
Dale Johannesen8593e412007-04-29 19:19:30 +0000548 // In thumb mode, if this block is a constpool island, we may need padding
549 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000550 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000551 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000552 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
553 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000554 MBBSize += 2;
555
Evan Chenga8e29892007-01-19 07:51:42 +0000556 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000557 BBOffsets.push_back(Offset);
558 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000559 }
560}
561
Evan Chenga8e29892007-01-19 07:51:42 +0000562/// GetOffsetOf - Return the current offset of the specified machine instruction
563/// from the start of the function. This offset changes as stuff is moved
564/// around inside the function.
565unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
566 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000567
Evan Chenga8e29892007-01-19 07:51:42 +0000568 // The offset is composed of two things: the sum of the sizes of all MBB's
569 // before this instruction's block, and the offset from the start of the block
570 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000571 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000572
Dale Johannesen8593e412007-04-29 19:19:30 +0000573 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
574 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000575 if (isThumb &&
576 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000577 Offset%4 != 0)
578 Offset += 2;
579
Evan Chenga8e29892007-01-19 07:51:42 +0000580 // Sum instructions before MI in MBB.
581 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
582 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
583 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000584 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000585 }
586}
587
588/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
589/// ID.
590static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
591 const MachineBasicBlock *RHS) {
592 return LHS->getNumber() < RHS->getNumber();
593}
594
595/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
596/// machine function, it upsets all of the block numbers. Renumber the blocks
597/// and update the arrays that parallel this numbering.
598void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
599 // Renumber the MBB's to keep them consequtive.
600 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000601
Evan Chenga8e29892007-01-19 07:51:42 +0000602 // Insert a size into BBSizes to align it properly with the (newly
603 // renumbered) block numbers.
604 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000605
606 // Likewise for BBOffsets.
607 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000608
609 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000610 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000611 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000612 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
613 CompareMBBNumbers);
614 WaterList.insert(IP, NewBB);
615}
616
617
618/// Split the basic block containing MI into two blocks, which are joined by
619/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000620/// account for this change and returns the newly created block.
621MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000622 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000623 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000624
625 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000626 MachineBasicBlock *NewBB =
627 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000628 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000629 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000630
Evan Chenga8e29892007-01-19 07:51:42 +0000631 // Splice the instructions starting with MI over to NewBB.
632 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000633
Evan Chenga8e29892007-01-19 07:51:42 +0000634 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000635 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000636 // There doesn't seem to be meaningful DebugInfo available; this doesn't
637 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000638 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
639 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000640 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000641
Evan Chenga8e29892007-01-19 07:51:42 +0000642 // Update the CFG. All succs of OrigBB are now succs of NewBB.
643 while (!OrigBB->succ_empty()) {
644 MachineBasicBlock *Succ = *OrigBB->succ_begin();
645 OrigBB->removeSuccessor(Succ);
646 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000647
Evan Chenga8e29892007-01-19 07:51:42 +0000648 // This pass should be run after register allocation, so there should be no
649 // PHI nodes to update.
650 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
651 && "PHI nodes should be eliminated by now!");
652 }
Bob Wilson84945262009-05-12 17:09:30 +0000653
Evan Chenga8e29892007-01-19 07:51:42 +0000654 // OrigBB branches to NewBB.
655 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000656
Evan Chenga8e29892007-01-19 07:51:42 +0000657 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000658 // This is almost the same as UpdateForInsertedWaterBlock, except that
659 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000660 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000661
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000662 // Insert a size into BBSizes to align it properly with the (newly
663 // renumbered) block numbers.
664 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000665
Dale Johannesen99c49a42007-02-25 00:47:03 +0000666 // Likewise for BBOffsets.
667 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
668
Bob Wilson84945262009-05-12 17:09:30 +0000669 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000670 // available water after it (but not if it's already there, which happens
671 // when splitting before a conditional branch that is followed by an
672 // unconditional branch - in that case we want to insert NewBB).
673 std::vector<MachineBasicBlock*>::iterator IP =
674 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
675 CompareMBBNumbers);
676 MachineBasicBlock* WaterBB = *IP;
677 if (WaterBB == OrigBB)
678 WaterList.insert(next(IP), NewBB);
679 else
680 WaterList.insert(IP, OrigBB);
681
Dale Johannesen8593e412007-04-29 19:19:30 +0000682 // Figure out how large the first NewMBB is. (It cannot
683 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000684 unsigned NewBBSize = 0;
685 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
686 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000687 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000688
Dale Johannesen99c49a42007-02-25 00:47:03 +0000689 unsigned OrigBBI = OrigBB->getNumber();
690 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000691 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000692 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000693
Evan Chenga8e29892007-01-19 07:51:42 +0000694 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000695 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000696 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000697 BBSizes[OrigBBI] -= NewBBSize - delta;
698
699 // ...and adjust BBOffsets for NewBB accordingly.
700 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
701
702 // All BBOffsets following these blocks must be modified.
703 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000704
705 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000706}
707
Dale Johannesen8593e412007-04-29 19:19:30 +0000708/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000709/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000710/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000711bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000712 unsigned TrialOffset, unsigned MaxDisp,
713 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000714 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
715 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000716 // Effectively, the valid range of displacements is 2 bytes smaller for such
717 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000718 unsigned TotalAdj = 0;
719 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000720 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000721 TotalAdj = 2;
722 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000723 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000724 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000725 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000726 TotalAdj += 2;
727 }
728
729 // In Thumb2 mode, later branch adjustments can shift instructions up and
730 // cause alignment change. In the worst case scenario this can cause the
731 // user's effective address to be subtracted by 2 and the CPE's address to
732 // be plus 2.
733 if (isThumb2 && TotalAdj != 4)
734 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000735
Dale Johannesen99c49a42007-02-25 00:47:03 +0000736 if (UserOffset <= TrialOffset) {
737 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000738 if (TrialOffset - UserOffset <= MaxDisp)
739 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000740 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000741 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000742 if (UserOffset - TrialOffset <= MaxDisp)
743 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000744 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000745 }
746 return false;
747}
748
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000749/// WaterIsInRange - Returns true if a CPE placed after the specified
750/// Water (a basic block) will be in range for the specific MI.
751
752bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000753 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000754 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000755 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000756 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000757
Dale Johannesend959aa42007-04-02 20:31:06 +0000758 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000759 // the offset of the instruction. (Currently applies only to ARM, so
760 // no alignment compensation attempted here.)
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.
933
Bob Wilson84945262009-05-12 17:09:30 +0000934MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000935 std::vector<MachineBasicBlock*>::iterator IP) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000936 DEBUG(errs() << "found water in range\n");
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).
943 return next(MachineFunction::iterator(WaterBB));
944}
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.
948/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000949/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000950/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000951/// water that will not introduce padding to water that will; within each
952/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000953bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000954 MachineBasicBlock** NewMBB) {
955 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
956 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000957 if (!WaterList.empty()) {
958 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000959 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000960 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000961 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000962 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000963 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000964 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000965 // This is valid Water, but would introduce padding. Remember
966 // it in case we don't find any Water that doesn't do this.
967 if (!WaterBBThatWouldPad) {
968 WaterBBThatWouldPad = WaterBB;
969 IPThatWouldPad = IP;
970 }
971 } else {
972 *NewMBB = AcceptWater(WaterBB, IP);
973 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000974 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000975 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000976 if (IP == B)
977 break;
978 }
979 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000980 if (isThumb && WaterBBThatWouldPad) {
981 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
982 return true;
983 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000984 return false;
985}
986
Bob Wilson84945262009-05-12 17:09:30 +0000987/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000988/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
989/// block is used if in range, and the conditional branch munged so control
990/// flow is correct. Otherwise the block is split to create a hole with an
991/// unconditional branch around it. In either case *NewMBB is set to a
992/// block following which the new island can be inserted (the WaterList
993/// is not adjusted).
994
Bob Wilson84945262009-05-12 17:09:30 +0000995void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000996 unsigned UserOffset, MachineBasicBlock** NewMBB) {
997 CPUser &U = CPUsers[CPUserIndex];
998 MachineInstr *UserMI = U.MI;
999 MachineInstr *CPEMI = U.CPEMI;
1000 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001001 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001002 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001003 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001004
1005 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +00001006 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-07-23 18:27:47 +00001007 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
1008 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001009 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +00001010 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +00001011 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +00001013 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1014 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001015 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001016 if (&UserMBB->back() == UserMI)
1017 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1018 *NewMBB = next(MachineFunction::iterator(UserMBB));
1019 // Add an unconditional branch from UserMBB to fallthrough block.
1020 // Record it for branch lengthening; this new branch will not get out of
1021 // range, but if the preceding conditional branch is out of range, the
1022 // targets will be exchanged, and the altered branch may be out of
1023 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001024 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001025 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1026 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001027 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001028 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001029 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001030 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001031 BBSizes[UserMBB->getNumber()] += delta;
1032 AdjustBBOffsetsAfter(UserMBB, delta);
1033 } else {
1034 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001035 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001036 // and constant pool entries are 4 bytes: if instruction I references
1037 // island CPE, and instruction I+1 references CPE', it will
1038 // not work well to put CPE as far forward as possible, since then
1039 // CPE' cannot immediately follow it (that location is 2 bytes
1040 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001041 // a new island. So, we make a first guess, then walk through the
1042 // instructions between the one currently being looked at and the
1043 // possible insertion point, and make sure any other instructions
1044 // that reference CPEs will be able to use the same island area;
1045 // if not, we back up the insertion point.
1046
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001047 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001048 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001049 // island is handled inside OffsetIsInRange.
1050 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001051 // This could point off the end of the block if we've already got
1052 // constant pool entries following this block; only the last one is
1053 // in the water list. Back past any possible branches (allow for a
1054 // conditional and a maximally long unconditional).
1055 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001056 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001057 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001058 unsigned EndInsertOffset = BaseInsertOffset +
1059 CPEMI->getOperand(2).getImm();
1060 MachineBasicBlock::iterator MI = UserMI;
1061 ++MI;
1062 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001063 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001064 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001065 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001066 MI = next(MI)) {
1067 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001068 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001069 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001070 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1071 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1072 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001073 }
1074 // This is overly conservative, as we don't account for CPEMIs
1075 // being reused within the block, but it doesn't matter much.
1076 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1077 CPUIndex++;
1078 }
1079 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001080 DEBUG(errs() << "Split in middle of big block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001081 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1082 }
1083}
1084
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001085/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001086/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001087/// place in-range. Return true if we changed any addresses (thus must run
1088/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001089bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001090 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001091 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001092 MachineInstr *UserMI = U.MI;
1093 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001094 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001095 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001096 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001097 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001098 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001100
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101 // See if the current entry is within range, or there is a clone of it
1102 // in range.
1103 int result = LookForExistingCPEntry(U, UserOffset);
1104 if (result==1) return false;
1105 else if (result==2) return true;
1106
1107 // No existing clone of this CPE is within range.
1108 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001109 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001110
1111 // Look for water where we can place this CPE. We look for the farthest one
1112 // away that will work. Forward references only for now (although later
1113 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001114
Dale Johannesen8593e412007-04-29 19:19:30 +00001115 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001116 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001117 DEBUG(errs() << "No water found\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001118 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001119 }
1120
1121 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001122 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1123 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001124
1125 // Update internal data structures to account for the newly inserted MBB.
1126 UpdateForInsertedWaterBlock(NewIsland);
1127
1128 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001129 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001130
1131 // Now that we have an island to add the CPE to, clone the original CPE and
1132 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001133 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1134 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001135 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001136 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001137 NumCPEs++;
1138
Dale Johannesen8593e412007-04-29 19:19:30 +00001139 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001140 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001141 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001142 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001143 // Increase the size of the island block to account for the new entry.
1144 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001145 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001146
Evan Chenga8e29892007-01-19 07:51:42 +00001147 // Finally, change the CPI in the instruction operand to be ID.
1148 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001149 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001150 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001151 break;
1152 }
Bob Wilson84945262009-05-12 17:09:30 +00001153
Chris Lattner705e07f2009-08-23 03:41:05 +00001154 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1155 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001156
Evan Chenga8e29892007-01-19 07:51:42 +00001157 return true;
1158}
1159
Evan Chenged884f32007-04-03 23:39:48 +00001160/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1161/// sizes and offsets of impacted basic blocks.
1162void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1163 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001164 unsigned Size = CPEMI->getOperand(2).getImm();
1165 CPEMI->eraseFromParent();
1166 BBSizes[CPEBB->getNumber()] -= Size;
1167 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001168 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001169 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001170 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001171 // empty, so fix this.
1172 // All succeeding offsets have the current size value added in, fix this.
1173 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001174 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001175 BBSizes[CPEBB->getNumber()] = 0;
1176 }
Evan Chenged884f32007-04-03 23:39:48 +00001177 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001178 AdjustBBOffsetsAfter(CPEBB, -Size);
1179 // An island has only one predecessor BB and one successor BB. Check if
1180 // this BB's predecessor jumps directly to this BB's successor. This
1181 // shouldn't happen currently.
1182 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1183 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001184}
1185
1186/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1187/// are zero.
1188bool ARMConstantIslands::RemoveUnusedCPEntries() {
1189 unsigned MadeChange = false;
1190 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1191 std::vector<CPEntry> &CPEs = CPEntries[i];
1192 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1193 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1194 RemoveDeadCPEMI(CPEs[j].CPEMI);
1195 CPEs[j].CPEMI = NULL;
1196 MadeChange = true;
1197 }
1198 }
Bob Wilson84945262009-05-12 17:09:30 +00001199 }
Evan Chenged884f32007-04-03 23:39:48 +00001200 return MadeChange;
1201}
1202
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001203/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001204/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001205bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1206 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001207 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001208 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001209 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001210
Chris Lattner705e07f2009-08-23 03:41:05 +00001211 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1212 << " from BB#" << MI->getParent()->getNumber()
1213 << " max delta=" << MaxDisp
1214 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1215 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001216
Dale Johannesen8593e412007-04-29 19:19:30 +00001217 if (BrOffset <= DestOffset) {
1218 // Branch before the Dest.
1219 if (DestOffset-BrOffset <= MaxDisp)
1220 return true;
1221 } else {
1222 if (BrOffset-DestOffset <= MaxDisp)
1223 return true;
1224 }
1225 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001226}
1227
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001228/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1229/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001230bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001231 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001232 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001233
Evan Chengc0dbec72007-01-31 19:57:44 +00001234 // Check to see if the DestBB is already in-range.
1235 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001236 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001237
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001238 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001239 return FixUpUnconditionalBr(MF, Br);
1240 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001241}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001242
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001243/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1244/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001245/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001246/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001247bool
Evan Cheng5657c012009-07-29 02:18:14 +00001248ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001249 MachineInstr *MI = Br.MI;
1250 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001251 if (!isThumb1)
1252 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001253
1254 // Use BL to implement far jump.
1255 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001256 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001257 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001258 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001259 HasFarJump = true;
1260 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001261
Chris Lattner705e07f2009-08-23 03:41:05 +00001262 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001263
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001264 return true;
1265}
1266
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001267/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001268/// far away to fit in its displacement field. It is converted to an inverse
1269/// conditional branch + an unconditional branch to the destination.
1270bool
Evan Cheng5657c012009-07-29 02:18:14 +00001271ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001272 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001273 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001274
Bob Wilson39bf0512009-05-12 17:35:29 +00001275 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001276 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001277 // blt L1
1278 // =>
1279 // bge L2
1280 // b L1
1281 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001282 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001283 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001284 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001285
1286 // If the branch is at the end of its MBB and that has a fall-through block,
1287 // direct the updated conditional branch to the fall-through block. Otherwise,
1288 // split the MBB before the next instruction.
1289 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001290 MachineInstr *BMI = &MBB->back();
1291 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001292
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001293 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001294 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001295 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001296 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001297 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001298 // condition and swap destinations:
1299 // beq L1
1300 // b L2
1301 // =>
1302 // bne L2
1303 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001304 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001305 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001306 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1307 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001308 BMI->getOperand(0).setMBB(DestBB);
1309 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001310 MI->getOperand(1).setImm(CC);
1311 return true;
1312 }
1313 }
1314 }
1315
1316 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001317 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001318 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001319 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001320 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001321 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001322 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1323 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001324 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001325 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001326 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001327 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001328
Chris Lattner893e1c92009-08-23 06:49:22 +00001329 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1330 << " also invert condition and change dest. to BB#"
1331 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001332
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001333 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001334 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001335 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1336 TII->get(MI->getOpcode()))
1337 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001338 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001339 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001340 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001341 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001342 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001343 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001344
1345 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001346 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001347 MI->eraseFromParent();
1348
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001349 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001350 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001351 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001352 return true;
1353}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001354
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001355/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001356/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1357/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001358bool ARMConstantIslands::UndoLRSpillRestore() {
1359 bool MadeChange = false;
1360 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1361 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001362 // First two operands are predicates, the third is a zero since there
1363 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001364 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001365 MI->getOperand(3).getReg() == ARM::PC &&
1366 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001367 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001368 MI->eraseFromParent();
1369 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001370 }
1371 }
1372 return MadeChange;
1373}
Evan Cheng5657c012009-07-29 02:18:14 +00001374
Evan Chenga1efbbd2009-08-14 00:32:16 +00001375bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1376 bool MadeChange = false;
1377
1378 // Shrink ADR and LDR from constantpool.
1379 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1380 CPUser &U = CPUsers[i];
1381 unsigned Opcode = U.MI->getOpcode();
1382 unsigned NewOpc = 0;
1383 unsigned Scale = 1;
1384 unsigned Bits = 0;
1385 switch (Opcode) {
1386 default: break;
1387 case ARM::t2LEApcrel:
1388 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1389 NewOpc = ARM::tLEApcrel;
1390 Bits = 8;
1391 Scale = 4;
1392 }
1393 break;
1394 case ARM::t2LDRpci:
1395 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1396 NewOpc = ARM::tLDRpci;
1397 Bits = 8;
1398 Scale = 4;
1399 }
1400 break;
1401 }
1402
1403 if (!NewOpc)
1404 continue;
1405
1406 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1407 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1408 // FIXME: Check if offset is multiple of scale if scale is not 4.
1409 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1410 U.MI->setDesc(TII->get(NewOpc));
1411 MachineBasicBlock *MBB = U.MI->getParent();
1412 BBSizes[MBB->getNumber()] -= 2;
1413 AdjustBBOffsetsAfter(MBB, -2);
1414 ++NumT2CPShrunk;
1415 MadeChange = true;
1416 }
1417 }
1418
Evan Chenga1efbbd2009-08-14 00:32:16 +00001419 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001420 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001421 return MadeChange;
1422}
1423
1424bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001425 bool MadeChange = false;
1426
1427 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1428 ImmBranch &Br = ImmBranches[i];
1429 unsigned Opcode = Br.MI->getOpcode();
1430 unsigned NewOpc = 0;
1431 unsigned Scale = 1;
1432 unsigned Bits = 0;
1433 switch (Opcode) {
1434 default: break;
1435 case ARM::t2B:
1436 NewOpc = ARM::tB;
1437 Bits = 11;
1438 Scale = 2;
1439 break;
1440 case ARM::t2Bcc:
1441 NewOpc = ARM::tBcc;
1442 Bits = 8;
1443 Scale = 2;
1444 break;
1445 }
1446 if (!NewOpc)
1447 continue;
1448
1449 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1450 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1451 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1452 Br.MI->setDesc(TII->get(NewOpc));
1453 MachineBasicBlock *MBB = Br.MI->getParent();
1454 BBSizes[MBB->getNumber()] -= 2;
1455 AdjustBBOffsetsAfter(MBB, -2);
1456 ++NumT2BrShrunk;
1457 MadeChange = true;
1458 }
1459 }
1460
1461 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001462}
1463
1464
1465/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1466/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001467bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1468 bool MadeChange = false;
1469
1470 // FIXME: After the tables are shrunk, can we get rid some of the
1471 // constantpool tables?
1472 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1473 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1474 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1475 MachineInstr *MI = T2JumpTables[i];
1476 const TargetInstrDesc &TID = MI->getDesc();
1477 unsigned NumOps = TID.getNumOperands();
1478 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1479 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1480 unsigned JTI = JTOP.getIndex();
1481 assert(JTI < JT.size());
1482
1483 bool ByteOk = true;
1484 bool HalfWordOk = true;
1485 unsigned JTOffset = GetOffsetOf(MI) + 4;
1486 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1487 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1488 MachineBasicBlock *MBB = JTBBs[j];
1489 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001490 // Negative offset is not ok. FIXME: We should change BB layout to make
1491 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001492 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001493 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001494 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001495 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001496 HalfWordOk = false;
1497 if (!ByteOk && !HalfWordOk)
1498 break;
1499 }
1500
1501 if (ByteOk || HalfWordOk) {
1502 MachineBasicBlock *MBB = MI->getParent();
1503 unsigned BaseReg = MI->getOperand(0).getReg();
1504 bool BaseRegKill = MI->getOperand(0).isKill();
1505 if (!BaseRegKill)
1506 continue;
1507 unsigned IdxReg = MI->getOperand(1).getReg();
1508 bool IdxRegKill = MI->getOperand(1).isKill();
1509 MachineBasicBlock::iterator PrevI = MI;
1510 if (PrevI == MBB->begin())
1511 continue;
1512
1513 MachineInstr *AddrMI = --PrevI;
1514 bool OptOk = true;
1515 // Examine the instruction that calculate the jumptable entry address.
1516 // If it's not the one just before the t2BR_JT, we won't delete it, then
1517 // it's not worth doing the optimization.
1518 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1519 const MachineOperand &MO = AddrMI->getOperand(k);
1520 if (!MO.isReg() || !MO.getReg())
1521 continue;
1522 if (MO.isDef() && MO.getReg() != BaseReg) {
1523 OptOk = false;
1524 break;
1525 }
1526 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1527 OptOk = false;
1528 break;
1529 }
1530 }
1531 if (!OptOk)
1532 continue;
1533
Evan Chenga1efbbd2009-08-14 00:32:16 +00001534 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1535 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001536 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001537 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1538 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001539 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001540 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001541
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001542 if (!OptOk)
1543 continue;
1544
1545 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1546 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1547 .addReg(IdxReg, getKillRegState(IdxRegKill))
1548 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1549 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1550 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1551 // is 2-byte aligned. For now, asm printer will fix it up.
1552 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1553 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1554 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1555 OrigSize += TII->GetInstSizeInBytes(MI);
1556
1557 AddrMI->eraseFromParent();
1558 LeaMI->eraseFromParent();
1559 MI->eraseFromParent();
1560
1561 int delta = OrigSize - NewSize;
1562 BBSizes[MBB->getNumber()] -= delta;
1563 AdjustBBOffsetsAfter(MBB, -delta);
1564
1565 ++NumTBs;
1566 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001567 }
1568 }
1569
1570 return MadeChange;
1571}