blob: b0bd04bade40aa8196dfadb2a4954bf9f2ceaff1 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000034using namespace llvm;
35
Evan Chenga1efbbd2009-08-14 00:32:16 +000036STATISTIC(NumCPEs, "Number of constpool entries");
37STATISTIC(NumSplit, "Number of uncond branches inserted");
38STATISTIC(NumCBrFixed, "Number of cond branches fixed");
39STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
40STATISTIC(NumTBs, "Number of table branches generated");
41STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000042STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chenga8e29892007-01-19 07:51:42 +000043
44namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000045 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000046 /// requires constant pool entries to be scattered among the instructions
47 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000048 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000049 /// special instructions.
50 ///
51 /// The terminology used in this pass includes:
52 /// Islands - Clumps of constants placed in the function.
53 /// Water - Potential places where an island could be formed.
54 /// CPE - A constant pool entry that has been placed somewhere, which
55 /// tracks a list of users.
56 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000057 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000058 /// by MBB Number. The two-byte pads required for Thumb alignment are
59 /// counted as part of the following block (i.e., the offset and size for
60 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000061 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000062
Dale Johannesen99c49a42007-02-25 00:47:03 +000063 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000064 /// The two-byte pads required for Thumb alignment are counted as part of
65 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000066 std::vector<unsigned> BBOffsets;
67
Evan Chenga8e29892007-01-19 07:51:42 +000068 /// WaterList - A sorted list of basic blocks where islands could be placed
69 /// (i.e. blocks that don't fall through to the following block, due
70 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000072
Bob Wilson034de5f2009-10-12 18:52:13 +000073 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
74
Evan Chenga8e29892007-01-19 07:51:42 +000075 /// CPUser - One user of a constant pool, keeping the machine instruction
76 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000077 /// allowed from the instruction to the CP. The HighWaterMark records the
78 /// highest basic block where a new CPEntry can be placed. To ensure this
79 /// pass terminates, the CP entries are initially placed at the end of the
80 /// function and then move monotonically to lower addresses. The
81 /// exception to this rule is when the current CP entry for a particular
82 /// CPUser is out of range, but there is another CP entry for the same
83 /// constant value in range. We want to use the existing in-range CP
84 /// entry, but if it later moves out of range, the search for new water
85 /// should resume where it left off. The HighWaterMark is used to record
86 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +000087 struct CPUser {
88 MachineInstr *MI;
89 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +000090 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +000091 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000092 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000093 bool IsSoImm;
94 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
95 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +000096 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
97 HighWaterMark = CPEMI->getParent();
98 }
Evan Chenga8e29892007-01-19 07:51:42 +000099 };
Bob Wilson84945262009-05-12 17:09:30 +0000100
Evan Chenga8e29892007-01-19 07:51:42 +0000101 /// CPUsers - Keep track of all of the machine instructions that use various
102 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000103 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000104
Evan Chengc99ef082007-02-09 20:54:44 +0000105 /// CPEntry - One per constant pool entry, keeping the machine instruction
106 /// pointer, the constpool index, and the number of CPUser's which
107 /// reference this entry.
108 struct CPEntry {
109 MachineInstr *CPEMI;
110 unsigned CPI;
111 unsigned RefCount;
112 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
113 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
114 };
115
116 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000117 /// instructions. For each original constpool index (i.e. those that
118 /// existed upon entry to this pass), it keeps a vector of entries.
119 /// Original elements are cloned as we go along; the clones are
120 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000121 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000122
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000123 /// ImmBranch - One per immediate branch, keeping the machine instruction
124 /// pointer, conditional or unconditional, the max displacement,
125 /// and (if isCond is true) the corresponding unconditional branch
126 /// opcode.
127 struct ImmBranch {
128 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000129 unsigned MaxDisp : 31;
130 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000131 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000132 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
133 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000134 };
135
Evan Cheng2706f972007-05-16 05:14:06 +0000136 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000138 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000139
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000140 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
141 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000142 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000143
Evan Cheng5657c012009-07-29 02:18:14 +0000144 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
145 SmallVector<MachineInstr*, 4> T2JumpTables;
146
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000147 /// HasFarJump - True if any far jump instruction has been emitted during
148 /// the branch fix up pass.
149 bool HasFarJump;
150
Evan Chenga8e29892007-01-19 07:51:42 +0000151 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000152 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000153 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000154 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000155 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000156 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000157 public:
Devang Patel19974732007-05-03 01:11:54 +0000158 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000159 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000160
Evan Cheng5657c012009-07-29 02:18:14 +0000161 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000162
163 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000164 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000165 }
Bob Wilson84945262009-05-12 17:09:30 +0000166
Evan Chenga8e29892007-01-19 07:51:42 +0000167 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000168 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000169 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000170 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000171 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000172 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000173 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000174 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000175 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000176 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000177 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000178 bool LookForWater(CPUser&U, unsigned UserOffset,
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000179 MachineBasicBlock *&NewMBB);
Bob Wilsond637c1a2009-10-12 20:37:23 +0000180 MachineBasicBlock *AcceptWater(water_iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000181 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000182 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000183 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000184 void RemoveDeadCPEMI(MachineInstr *CPEMI);
185 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000186 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000187 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
188 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000189 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000190 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000191 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000192 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000193 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000194 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
195 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
196 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000197 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000198 bool OptimizeThumb2Instructions(MachineFunction &MF);
199 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000200 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000201
Evan Chenga8e29892007-01-19 07:51:42 +0000202 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000203 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000204 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000205 };
Devang Patel19974732007-05-03 01:11:54 +0000206 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000207}
208
Dale Johannesen8593e412007-04-29 19:19:30 +0000209/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000210void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000211 assert(BBOffsets.size() == BBSizes.size());
212 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
213 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000214 if (!isThumb)
215 return;
216#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000217 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000218 MBBI != E; ++MBBI) {
219 MachineBasicBlock *MBB = MBBI;
220 if (!MBB->empty() &&
221 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
222 unsigned MBBId = MBB->getNumber();
223 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
224 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000225 }
226 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000227#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000228}
229
230/// print block size and offset information - debugging
231void ARMConstantIslands::dumpBBs() {
232 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000233 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
234 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000235 }
236}
237
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238/// createARMConstantIslandPass - returns an instance of the constpool
239/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000240FunctionPass *llvm::createARMConstantIslandPass() {
241 return new ARMConstantIslands();
242}
243
Evan Cheng5657c012009-07-29 02:18:14 +0000244bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
245 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000246
Evan Cheng5657c012009-07-29 02:18:14 +0000247 TII = MF.getTarget().getInstrInfo();
248 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000249 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
250
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000251 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000252 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000253 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000254
255 HasFarJump = false;
256
Evan Chenga8e29892007-01-19 07:51:42 +0000257 // Renumber all of the machine basic blocks in the function, guaranteeing that
258 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000259 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000260
Evan Chengd26b14c2009-07-31 18:28:05 +0000261 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000262 // This is so we can keep exact track of where the alignment padding goes.
263
Evan Chengd26b14c2009-07-31 18:28:05 +0000264 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000265 // aligned.
266 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000267
Evan Chenga8e29892007-01-19 07:51:42 +0000268 // Perform the initial placement of the constant pool entries. To start with,
269 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000270 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000271 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000272 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000273 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000274 AFI->setAlign(2U);
275 }
Bob Wilson84945262009-05-12 17:09:30 +0000276
Evan Chenga8e29892007-01-19 07:51:42 +0000277 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000278 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000279
Evan Chenga8e29892007-01-19 07:51:42 +0000280 // Do the initial scan of the function, building up information about the
281 // sizes of each block, the location of all the water, and finding all of the
282 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000283 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000284 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000285
Evan Chenged884f32007-04-03 23:39:48 +0000286 /// Remove dead constant pool entries.
287 RemoveUnusedCPEntries();
288
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000289 // Iteratively place constant pool entries and fix up branches until there
290 // is no change.
291 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000292 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000293 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000294 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000295 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000296 CPChange |= HandleConstantPoolUser(MF, i);
297 if (CPChange && ++NoCPIters > 30)
298 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000299 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000300
301 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000302 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000303 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
304 if (BRChange && ++NoBRIters > 30)
305 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000306 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000307
308 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000309 break;
310 MadeChange = true;
311 }
Evan Chenged884f32007-04-03 23:39:48 +0000312
Evan Chenga1efbbd2009-08-14 00:32:16 +0000313 // Shrink 32-bit Thumb2 branch, load, and store instructions.
314 if (isThumb2)
315 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000316
Dale Johannesen8593e412007-04-29 19:19:30 +0000317 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000318 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000319
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000320 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
321 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000322 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000323 MadeChange |= UndoLRSpillRestore();
324
Evan Chenga8e29892007-01-19 07:51:42 +0000325 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000326 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000327 WaterList.clear();
328 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000329 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000330 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000331 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000332 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000333
334 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000335}
336
337/// DoInitialPlacement - Perform the initial placement of the constant pool
338/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000339void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000340 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000341 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000342 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
343 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000344
Evan Chenga8e29892007-01-19 07:51:42 +0000345 // Add all of the constants from the constant pool to the end block, use an
346 // identity mapping of CPI's to CPE's.
347 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000348 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000349
Evan Cheng5657c012009-07-29 02:18:14 +0000350 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000351 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000352 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000353 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
354 // we would have to pad them out or something so that instructions stay
355 // aligned.
356 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
357 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000358 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000359 .addImm(i).addConstantPoolIndex(i).addImm(Size);
360 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000361
362 // Add a new CPEntry, but no corresponding CPUser yet.
363 std::vector<CPEntry> CPEs;
364 CPEs.push_back(CPEntry(CPEMI, i));
365 CPEntries.push_back(CPEs);
366 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000367 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
368 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000369 }
370}
371
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000372/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000373/// into the block immediately after it.
374static bool BBHasFallthrough(MachineBasicBlock *MBB) {
375 // Get the next machine basic block in the function.
376 MachineFunction::iterator MBBI = MBB;
377 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
378 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000379
Evan Chenga8e29892007-01-19 07:51:42 +0000380 MachineBasicBlock *NextBB = next(MBBI);
381 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
382 E = MBB->succ_end(); I != E; ++I)
383 if (*I == NextBB)
384 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000385
Evan Chenga8e29892007-01-19 07:51:42 +0000386 return false;
387}
388
Evan Chengc99ef082007-02-09 20:54:44 +0000389/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
390/// look up the corresponding CPEntry.
391ARMConstantIslands::CPEntry
392*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
393 const MachineInstr *CPEMI) {
394 std::vector<CPEntry> &CPEs = CPEntries[CPI];
395 // Number of entries per constpool index should be small, just do a
396 // linear search.
397 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
398 if (CPEs[i].CPEMI == CPEMI)
399 return &CPEs[i];
400 }
401 return NULL;
402}
403
Evan Chenga8e29892007-01-19 07:51:42 +0000404/// InitialFunctionScan - Do the initial scan of the function, building up
405/// information about the sizes of each block, the location of all the water,
406/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000407void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000408 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000409 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000410 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000411 MBBI != E; ++MBBI) {
412 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000413
Evan Chenga8e29892007-01-19 07:51:42 +0000414 // If this block doesn't fall through into the next MBB, then this is
415 // 'water' that a constant pool island could be placed.
416 if (!BBHasFallthrough(&MBB))
417 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000418
Evan Chenga8e29892007-01-19 07:51:42 +0000419 unsigned MBBSize = 0;
420 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
421 I != E; ++I) {
422 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000423 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000424
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000425 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000426 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000427 bool isCond = false;
428 unsigned Bits = 0;
429 unsigned Scale = 1;
430 int UOpc = Opc;
431 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000432 default:
433 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000434 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000435 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000436 // be right, functions containing these must be 4-byte aligned.
437 AFI->setAlign(2U);
438 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000439 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000440 MBBSize += 2; // padding
441 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000442 case ARM::t2BR_JT:
443 T2JumpTables.push_back(I);
444 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000445 case ARM::Bcc:
446 isCond = true;
447 UOpc = ARM::B;
448 // Fallthrough
449 case ARM::B:
450 Bits = 24;
451 Scale = 4;
452 break;
453 case ARM::tBcc:
454 isCond = true;
455 UOpc = ARM::tB;
456 Bits = 8;
457 Scale = 2;
458 break;
459 case ARM::tB:
460 Bits = 11;
461 Scale = 2;
462 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000463 case ARM::t2Bcc:
464 isCond = true;
465 UOpc = ARM::t2B;
466 Bits = 20;
467 Scale = 2;
468 break;
469 case ARM::t2B:
470 Bits = 24;
471 Scale = 2;
472 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000473 }
Evan Chengb43216e2007-02-01 10:16:15 +0000474
475 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000476 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000477 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000478 }
479
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000480 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
481 PushPopMIs.push_back(I);
482
Evan Chengd3d9d662009-07-23 18:27:47 +0000483 if (Opc == ARM::CONSTPOOL_ENTRY)
484 continue;
485
Evan Chenga8e29892007-01-19 07:51:42 +0000486 // Scan the instructions for constant pool operands.
487 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000488 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000489 // We found one. The addressing mode tells us the max displacement
490 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000491
Evan Chenga8e29892007-01-19 07:51:42 +0000492 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000493 unsigned Bits = 0;
494 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000495 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000496 bool IsSoImm = false;
497
498 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000499 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000500 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000501 break;
502
503 // Taking the address of a CP entry.
504 case ARM::LEApcrel:
505 // This takes a SoImm, which is 8 bit immediate rotated. We'll
506 // pretend the maximum offset is 255 * 4. Since each instruction
507 // 4 byte wide, this is always correct. We'llc heck for other
508 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000509 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000510 Scale = 4;
511 NegOk = true;
512 IsSoImm = true;
513 break;
514 case ARM::t2LEApcrel:
515 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000516 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000517 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000518 case ARM::tLEApcrel:
519 Bits = 8;
520 Scale = 4;
521 break;
522
523 case ARM::LDR:
524 case ARM::LDRcp:
525 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000526 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000527 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000528 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000529
530 case ARM::tLDRpci:
531 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000532 Bits = 8;
533 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000534 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000535
536 case ARM::FLDD:
537 case ARM::FLDS:
538 Bits = 8;
539 Scale = 4; // +-(offset_8*4)
540 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000541 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000542 }
Evan Chengb43216e2007-02-01 10:16:15 +0000543
Evan Chenga8e29892007-01-19 07:51:42 +0000544 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000545 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000546 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000547 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000548 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000549
550 // Increment corresponding CPEntry reference count.
551 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
552 assert(CPE && "Cannot find a corresponding CPEntry!");
553 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000554
Evan Chenga8e29892007-01-19 07:51:42 +0000555 // Instructions can only use one CP entry, don't bother scanning the
556 // rest of the operands.
557 break;
558 }
559 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000560
Dale Johannesen8593e412007-04-29 19:19:30 +0000561 // In thumb mode, if this block is a constpool island, we may need padding
562 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000563 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000564 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000565 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
566 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000567 MBBSize += 2;
568
Evan Chenga8e29892007-01-19 07:51:42 +0000569 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000570 BBOffsets.push_back(Offset);
571 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000572 }
573}
574
Evan Chenga8e29892007-01-19 07:51:42 +0000575/// GetOffsetOf - Return the current offset of the specified machine instruction
576/// from the start of the function. This offset changes as stuff is moved
577/// around inside the function.
578unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
579 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000580
Evan Chenga8e29892007-01-19 07:51:42 +0000581 // The offset is composed of two things: the sum of the sizes of all MBB's
582 // before this instruction's block, and the offset from the start of the block
583 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000584 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000585
Dale Johannesen8593e412007-04-29 19:19:30 +0000586 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
587 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000588 if (isThumb &&
589 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000590 Offset%4 != 0)
591 Offset += 2;
592
Evan Chenga8e29892007-01-19 07:51:42 +0000593 // Sum instructions before MI in MBB.
594 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
595 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
596 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000597 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000598 }
599}
600
601/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
602/// ID.
603static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
604 const MachineBasicBlock *RHS) {
605 return LHS->getNumber() < RHS->getNumber();
606}
607
608/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
609/// machine function, it upsets all of the block numbers. Renumber the blocks
610/// and update the arrays that parallel this numbering.
611void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
612 // Renumber the MBB's to keep them consequtive.
613 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000614
Evan Chenga8e29892007-01-19 07:51:42 +0000615 // Insert a size into BBSizes to align it properly with the (newly
616 // renumbered) block numbers.
617 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000618
619 // Likewise for BBOffsets.
620 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000621
622 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000623 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000624 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000625 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
626 CompareMBBNumbers);
627 WaterList.insert(IP, NewBB);
628}
629
630
631/// Split the basic block containing MI into two blocks, which are joined by
632/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000633/// account for this change and returns the newly created block.
634MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000635 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000636 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000637
638 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000639 MachineBasicBlock *NewBB =
640 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000641 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000642 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000643
Evan Chenga8e29892007-01-19 07:51:42 +0000644 // Splice the instructions starting with MI over to NewBB.
645 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000646
Evan Chenga8e29892007-01-19 07:51:42 +0000647 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000648 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000649 // There doesn't seem to be meaningful DebugInfo available; this doesn't
650 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000651 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
652 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000653 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000654
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // Update the CFG. All succs of OrigBB are now succs of NewBB.
656 while (!OrigBB->succ_empty()) {
657 MachineBasicBlock *Succ = *OrigBB->succ_begin();
658 OrigBB->removeSuccessor(Succ);
659 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000660
Evan Chenga8e29892007-01-19 07:51:42 +0000661 // This pass should be run after register allocation, so there should be no
662 // PHI nodes to update.
663 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
664 && "PHI nodes should be eliminated by now!");
665 }
Bob Wilson84945262009-05-12 17:09:30 +0000666
Evan Chenga8e29892007-01-19 07:51:42 +0000667 // OrigBB branches to NewBB.
668 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000669
Evan Chenga8e29892007-01-19 07:51:42 +0000670 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000671 // This is almost the same as UpdateForInsertedWaterBlock, except that
672 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000673 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000674
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000675 // Insert a size into BBSizes to align it properly with the (newly
676 // renumbered) block numbers.
677 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000678
Dale Johannesen99c49a42007-02-25 00:47:03 +0000679 // Likewise for BBOffsets.
680 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
681
Bob Wilson84945262009-05-12 17:09:30 +0000682 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000683 // available water after it (but not if it's already there, which happens
684 // when splitting before a conditional branch that is followed by an
685 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000686 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000687 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
688 CompareMBBNumbers);
689 MachineBasicBlock* WaterBB = *IP;
690 if (WaterBB == OrigBB)
691 WaterList.insert(next(IP), NewBB);
692 else
693 WaterList.insert(IP, OrigBB);
694
Dale Johannesen8593e412007-04-29 19:19:30 +0000695 // Figure out how large the first NewMBB is. (It cannot
696 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000697 unsigned NewBBSize = 0;
698 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
699 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000700 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000701
Dale Johannesen99c49a42007-02-25 00:47:03 +0000702 unsigned OrigBBI = OrigBB->getNumber();
703 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000704 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000705 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000706
Evan Chenga8e29892007-01-19 07:51:42 +0000707 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000708 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000709 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000710 BBSizes[OrigBBI] -= NewBBSize - delta;
711
712 // ...and adjust BBOffsets for NewBB accordingly.
713 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
714
715 // All BBOffsets following these blocks must be modified.
716 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000717
718 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000719}
720
Dale Johannesen8593e412007-04-29 19:19:30 +0000721/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000722/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000723/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000724bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000725 unsigned TrialOffset, unsigned MaxDisp,
726 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000727 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
728 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000729 // Effectively, the valid range of displacements is 2 bytes smaller for such
730 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000731 unsigned TotalAdj = 0;
732 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000733 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000734 TotalAdj = 2;
735 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000736 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000737 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000738 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000739 TotalAdj += 2;
740 }
741
742 // In Thumb2 mode, later branch adjustments can shift instructions up and
743 // cause alignment change. In the worst case scenario this can cause the
744 // user's effective address to be subtracted by 2 and the CPE's address to
745 // be plus 2.
746 if (isThumb2 && TotalAdj != 4)
747 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000748
Dale Johannesen99c49a42007-02-25 00:47:03 +0000749 if (UserOffset <= TrialOffset) {
750 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000751 if (TrialOffset - UserOffset <= MaxDisp)
752 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000753 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000754 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000755 if (UserOffset - TrialOffset <= MaxDisp)
756 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000757 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000758 }
759 return false;
760}
761
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000762/// WaterIsInRange - Returns true if a CPE placed after the specified
763/// Water (a basic block) will be in range for the specific MI.
764
765bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000766 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000767 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000768 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000769 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000770
Dale Johannesend959aa42007-04-02 20:31:06 +0000771 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000772 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000773 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000774 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000775
Evan Chengd3d9d662009-07-23 18:27:47 +0000776 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000777}
778
779/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000780/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000781bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000782 MachineInstr *CPEMI, unsigned MaxDisp,
783 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000784 unsigned CPEOffset = GetOffsetOf(CPEMI);
785 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000786
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000787 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000788 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
789 << " max delta=" << MaxDisp
790 << " insn address=" << UserOffset
791 << " CPE address=" << CPEOffset
792 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000793 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000794
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000795 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000796}
797
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000798#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000799/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
800/// unconditionally branches to its only successor.
801static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
802 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
803 return false;
804
805 MachineBasicBlock *Succ = *MBB->succ_begin();
806 MachineBasicBlock *Pred = *MBB->pred_begin();
807 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000808 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
809 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000810 return PredMI->getOperand(0).getMBB() == Succ;
811 return false;
812}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000813#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000814
Bob Wilson84945262009-05-12 17:09:30 +0000815void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000816 int delta) {
817 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000818 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
819 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000820 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000821 // If some existing blocks have padding, adjust the padding as needed, a
822 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000823 if (!isThumb)
824 continue;
825 MachineBasicBlock *MBB = MBBI;
826 if (!MBB->empty()) {
827 // Constant pool entries require padding.
828 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000829 unsigned OldOffset = BBOffsets[i] - delta;
830 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000831 // add new padding
832 BBSizes[i] += 2;
833 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000834 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000835 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000836 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000837 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000838 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000839 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000840 // Thumb1 jump tables require padding. They should be at the end;
841 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000842 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000843 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000844 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
845 unsigned OldMIOffset = NewMIOffset - delta;
846 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000847 // remove existing padding
848 BBSizes[i] -= 2;
849 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000850 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000851 // add new padding
852 BBSizes[i] += 2;
853 delta += 2;
854 }
855 }
856 if (delta==0)
857 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000858 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000859 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000860 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000861}
862
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000863/// DecrementOldEntry - find the constant pool entry with index CPI
864/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000865/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000866/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000867
Evan Chenged884f32007-04-03 23:39:48 +0000868bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000869 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000870 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
871 assert(CPE && "Unexpected!");
872 if (--CPE->RefCount == 0) {
873 RemoveDeadCPEMI(CPEMI);
874 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000875 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000876 return true;
877 }
878 return false;
879}
880
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
882/// if not, see if an in-range clone of the CPE is in range, and if so,
883/// change the data structures so the user references the clone. Returns:
884/// 0 = no existing entry found
885/// 1 = entry found, and there were no code insertions or deletions
886/// 2 = entry found, and there were code insertions or deletions
887int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
888{
889 MachineInstr *UserMI = U.MI;
890 MachineInstr *CPEMI = U.CPEMI;
891
892 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000893 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000894 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000895 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000896 }
897
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000899 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000900 std::vector<CPEntry> &CPEs = CPEntries[CPI];
901 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
902 // We already tried this one
903 if (CPEs[i].CPEMI == CPEMI)
904 continue;
905 // Removing CPEs can leave empty entries, skip
906 if (CPEs[i].CPEMI == NULL)
907 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000908 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000909 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
910 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000911 // Point the CPUser node to the replacement
912 U.CPEMI = CPEs[i].CPEMI;
913 // Change the CPI in the instruction operand to refer to the clone.
914 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000915 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000916 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000917 break;
918 }
919 // Adjust the refcount of the clone...
920 CPEs[i].RefCount++;
921 // ...and the original. If we didn't remove the old entry, none of the
922 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000923 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000924 }
925 }
926 return 0;
927}
928
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000929/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
930/// the specific unconditional branch instruction.
931static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000932 switch (Opc) {
933 case ARM::tB:
934 return ((1<<10)-1)*2;
935 case ARM::t2B:
936 return ((1<<23)-1)*2;
937 default:
938 break;
939 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000940
David Goodwin5e47a9a2009-06-30 18:04:13 +0000941 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000942}
943
Dale Johannesen8593e412007-04-29 19:19:30 +0000944/// AcceptWater - Small amount of common code factored out of the following.
Bob Wilsond637c1a2009-10-12 20:37:23 +0000945///
946MachineBasicBlock *ARMConstantIslands::AcceptWater(water_iterator IP) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000947 DEBUG(errs() << "found water in range\n");
Bob Wilson4796ba22009-10-13 17:29:13 +0000948 MachineBasicBlock *WaterBB = *IP;
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 // Remove the original WaterList entry; we want subsequent
950 // insertions in this vicinity to go after the one we're
951 // about to insert. This considerably reduces the number
952 // of times we have to move the same CPE more than once.
953 WaterList.erase(IP);
954 // CPE goes before following block (NewMBB).
Bob Wilson4796ba22009-10-13 17:29:13 +0000955 return next(MachineFunction::iterator(WaterBB));
Dale Johannesen8593e412007-04-29 19:19:30 +0000956}
957
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000958/// LookForWater - look for an existing entry in the WaterList in which
959/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000960/// Returns true if found, false if not. If it returns true, NewMBB
Bob Wilsonf98032e2009-10-12 21:23:15 +0000961/// is set to the WaterList entry. For Thumb, prefer water that will not
962/// introduce padding to water that will. To ensure that this pass
963/// terminates, the CPE location for a particular CPUser is only allowed to
964/// move to a lower address, so search backward from the end of the list and
965/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000966bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilson9d16f2c2009-10-12 19:01:12 +0000967 MachineBasicBlock *&NewMBB) {
Bob Wilson3b757352009-10-12 19:04:03 +0000968 if (WaterList.empty())
969 return false;
970
Bob Wilson32c50e82009-10-12 20:45:53 +0000971 bool FoundWaterThatWouldPad = false;
972 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000973 for (water_iterator IP = prior(WaterList.end()),
974 B = WaterList.begin();; --IP) {
975 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonf98032e2009-10-12 21:23:15 +0000976 // Check if water is in range and at a lower address than the current one.
Bob Wilson549dda92009-10-15 05:52:29 +0000977 if (WaterBB->getNumber() < U.HighWaterMark->getNumber() &&
978 WaterIsInRange(UserOffset, WaterBB, U)) {
Bob Wilson3b757352009-10-12 19:04:03 +0000979 unsigned WBBId = WaterBB->getNumber();
980 if (isThumb &&
981 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
982 // This is valid Water, but would introduce padding. Remember
983 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +0000984 if (!FoundWaterThatWouldPad) {
985 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +0000986 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000987 }
Bob Wilson3b757352009-10-12 19:04:03 +0000988 } else {
Bob Wilsond637c1a2009-10-12 20:37:23 +0000989 NewMBB = AcceptWater(IP);
Bob Wilson3b757352009-10-12 19:04:03 +0000990 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +0000991 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000992 }
Bob Wilson3b757352009-10-12 19:04:03 +0000993 if (IP == B)
994 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000995 }
Bob Wilson32c50e82009-10-12 20:45:53 +0000996 if (FoundWaterThatWouldPad) {
Bob Wilsond637c1a2009-10-12 20:37:23 +0000997 NewMBB = AcceptWater(IPThatWouldPad);
Dale Johannesen8593e412007-04-29 19:19:30 +0000998 return true;
999 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001000 return false;
1001}
1002
Bob Wilson84945262009-05-12 17:09:30 +00001003/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001004/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1005/// block is used if in range, and the conditional branch munged so control
1006/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001007/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001008/// block following which the new island can be inserted (the WaterList
1009/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001010void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001011 unsigned UserOffset,
1012 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001013 CPUser &U = CPUsers[CPUserIndex];
1014 MachineInstr *UserMI = U.MI;
1015 MachineInstr *CPEMI = U.CPEMI;
1016 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001017 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001019 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020
Bob Wilson36fa5322009-10-15 05:10:36 +00001021 // If the block does not end in an unconditional branch already, and if the
1022 // end of the block is within range, make new water there. (The addition
1023 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1024 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001025 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001026 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001027 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1028 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001029 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001030 if (&UserMBB->back() == UserMI)
1031 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001032 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 // Add an unconditional branch from UserMBB to fallthrough block.
1034 // Record it for branch lengthening; this new branch will not get out of
1035 // range, but if the preceding conditional branch is out of range, the
1036 // targets will be exchanged, and the altered branch may be out of
1037 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001038 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001039 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001040 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001041 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001042 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001043 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001044 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001045 BBSizes[UserMBB->getNumber()] += delta;
1046 AdjustBBOffsetsAfter(UserMBB, delta);
1047 } else {
1048 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001049 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001050 // and constant pool entries are 4 bytes: if instruction I references
1051 // island CPE, and instruction I+1 references CPE', it will
1052 // not work well to put CPE as far forward as possible, since then
1053 // CPE' cannot immediately follow it (that location is 2 bytes
1054 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001055 // a new island. So, we make a first guess, then walk through the
1056 // instructions between the one currently being looked at and the
1057 // possible insertion point, and make sure any other instructions
1058 // that reference CPEs will be able to use the same island area;
1059 // if not, we back up the insertion point.
1060
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001061 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001062 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001063 // island is handled inside OffsetIsInRange.
1064 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001065 // This could point off the end of the block if we've already got
1066 // constant pool entries following this block; only the last one is
1067 // in the water list. Back past any possible branches (allow for a
1068 // conditional and a maximally long unconditional).
1069 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001070 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001071 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001072 unsigned EndInsertOffset = BaseInsertOffset +
1073 CPEMI->getOperand(2).getImm();
1074 MachineBasicBlock::iterator MI = UserMI;
1075 ++MI;
1076 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001077 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001078 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001079 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001080 MI = next(MI)) {
1081 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001082 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001083 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001084 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1085 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1086 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001087 }
1088 // This is overly conservative, as we don't account for CPEMIs
1089 // being reused within the block, but it doesn't matter much.
1090 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1091 CPUIndex++;
1092 }
1093 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001094 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001095 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001096 }
1097}
1098
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001100/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101/// place in-range. Return true if we changed any addresses (thus must run
1102/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001103bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001104 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001105 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001106 MachineInstr *UserMI = U.MI;
1107 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001108 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001109 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001110 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001111 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001112 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001114
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001115 // See if the current entry is within range, or there is a clone of it
1116 // in range.
1117 int result = LookForExistingCPEntry(U, UserOffset);
1118 if (result==1) return false;
1119 else if (result==2) return true;
1120
1121 // No existing clone of this CPE is within range.
1122 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001123 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001124
Bob Wilsonf98032e2009-10-12 21:23:15 +00001125 // Look for water where we can place this CPE.
Bob Wilson9d16f2c2009-10-12 19:01:12 +00001126 if (!LookForWater(U, UserOffset, NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001127 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001128 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001129 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001130 }
1131
1132 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001133 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1134 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001135
1136 // Update internal data structures to account for the newly inserted MBB.
1137 UpdateForInsertedWaterBlock(NewIsland);
1138
1139 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001140 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001141
1142 // Now that we have an island to add the CPE to, clone the original CPE and
1143 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001144 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001145 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1146 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001147 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001148 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001149 NumCPEs++;
1150
Dale Johannesen8593e412007-04-29 19:19:30 +00001151 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001152 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001153 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001154 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001155 // Increase the size of the island block to account for the new entry.
1156 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001157 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001158
Evan Chenga8e29892007-01-19 07:51:42 +00001159 // Finally, change the CPI in the instruction operand to be ID.
1160 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001161 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001162 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001163 break;
1164 }
Bob Wilson84945262009-05-12 17:09:30 +00001165
Chris Lattner705e07f2009-08-23 03:41:05 +00001166 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1167 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001168
Evan Chenga8e29892007-01-19 07:51:42 +00001169 return true;
1170}
1171
Evan Chenged884f32007-04-03 23:39:48 +00001172/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1173/// sizes and offsets of impacted basic blocks.
1174void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1175 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001176 unsigned Size = CPEMI->getOperand(2).getImm();
1177 CPEMI->eraseFromParent();
1178 BBSizes[CPEBB->getNumber()] -= Size;
1179 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001180 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001181 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001182 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001183 // empty, so fix this.
1184 // All succeeding offsets have the current size value added in, fix this.
1185 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001186 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001187 BBSizes[CPEBB->getNumber()] = 0;
1188 }
Evan Chenged884f32007-04-03 23:39:48 +00001189 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001190 AdjustBBOffsetsAfter(CPEBB, -Size);
1191 // An island has only one predecessor BB and one successor BB. Check if
1192 // this BB's predecessor jumps directly to this BB's successor. This
1193 // shouldn't happen currently.
1194 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1195 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001196}
1197
1198/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1199/// are zero.
1200bool ARMConstantIslands::RemoveUnusedCPEntries() {
1201 unsigned MadeChange = false;
1202 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1203 std::vector<CPEntry> &CPEs = CPEntries[i];
1204 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1205 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1206 RemoveDeadCPEMI(CPEs[j].CPEMI);
1207 CPEs[j].CPEMI = NULL;
1208 MadeChange = true;
1209 }
1210 }
Bob Wilson84945262009-05-12 17:09:30 +00001211 }
Evan Chenged884f32007-04-03 23:39:48 +00001212 return MadeChange;
1213}
1214
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001215/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001216/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001217bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1218 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001219 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001220 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001221 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001222
Chris Lattner705e07f2009-08-23 03:41:05 +00001223 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1224 << " from BB#" << MI->getParent()->getNumber()
1225 << " max delta=" << MaxDisp
1226 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1227 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001228
Dale Johannesen8593e412007-04-29 19:19:30 +00001229 if (BrOffset <= DestOffset) {
1230 // Branch before the Dest.
1231 if (DestOffset-BrOffset <= MaxDisp)
1232 return true;
1233 } else {
1234 if (BrOffset-DestOffset <= MaxDisp)
1235 return true;
1236 }
1237 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001238}
1239
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001240/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1241/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001242bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001243 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001244 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001245
Evan Chengc0dbec72007-01-31 19:57:44 +00001246 // Check to see if the DestBB is already in-range.
1247 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001248 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001249
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001250 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001251 return FixUpUnconditionalBr(MF, Br);
1252 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001253}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001254
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001255/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1256/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001257/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001258/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001259bool
Evan Cheng5657c012009-07-29 02:18:14 +00001260ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001261 MachineInstr *MI = Br.MI;
1262 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001263 if (!isThumb1)
1264 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001265
1266 // Use BL to implement far jump.
1267 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001268 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001269 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001270 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001271 HasFarJump = true;
1272 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001273
Chris Lattner705e07f2009-08-23 03:41:05 +00001274 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001275
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001276 return true;
1277}
1278
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001279/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001280/// far away to fit in its displacement field. It is converted to an inverse
1281/// conditional branch + an unconditional branch to the destination.
1282bool
Evan Cheng5657c012009-07-29 02:18:14 +00001283ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001284 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001285 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001286
Bob Wilson39bf0512009-05-12 17:35:29 +00001287 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001288 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001289 // blt L1
1290 // =>
1291 // bge L2
1292 // b L1
1293 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001294 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001295 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001296 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001297
1298 // If the branch is at the end of its MBB and that has a fall-through block,
1299 // direct the updated conditional branch to the fall-through block. Otherwise,
1300 // split the MBB before the next instruction.
1301 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001302 MachineInstr *BMI = &MBB->back();
1303 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001304
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001305 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001306 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001307 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001308 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001309 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001310 // condition and swap destinations:
1311 // beq L1
1312 // b L2
1313 // =>
1314 // bne L2
1315 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001316 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001317 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001318 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1319 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001320 BMI->getOperand(0).setMBB(DestBB);
1321 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001322 MI->getOperand(1).setImm(CC);
1323 return true;
1324 }
1325 }
1326 }
1327
1328 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001329 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001330 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001331 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001332 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001333 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001334 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1335 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001336 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001337 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001338 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001339 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001340
Chris Lattner893e1c92009-08-23 06:49:22 +00001341 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1342 << " also invert condition and change dest. to BB#"
1343 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001344
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001345 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001346 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001347 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1348 TII->get(MI->getOpcode()))
1349 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001350 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001351 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001352 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001353 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001354 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001355 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001356
1357 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001358 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001359 MI->eraseFromParent();
1360
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001361 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001362 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001363 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001364 return true;
1365}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001366
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001367/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001368/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1369/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001370bool ARMConstantIslands::UndoLRSpillRestore() {
1371 bool MadeChange = false;
1372 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1373 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001374 // First two operands are predicates, the third is a zero since there
1375 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001376 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001377 MI->getOperand(3).getReg() == ARM::PC &&
1378 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001379 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001380 MI->eraseFromParent();
1381 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001382 }
1383 }
1384 return MadeChange;
1385}
Evan Cheng5657c012009-07-29 02:18:14 +00001386
Evan Chenga1efbbd2009-08-14 00:32:16 +00001387bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1388 bool MadeChange = false;
1389
1390 // Shrink ADR and LDR from constantpool.
1391 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1392 CPUser &U = CPUsers[i];
1393 unsigned Opcode = U.MI->getOpcode();
1394 unsigned NewOpc = 0;
1395 unsigned Scale = 1;
1396 unsigned Bits = 0;
1397 switch (Opcode) {
1398 default: break;
1399 case ARM::t2LEApcrel:
1400 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1401 NewOpc = ARM::tLEApcrel;
1402 Bits = 8;
1403 Scale = 4;
1404 }
1405 break;
1406 case ARM::t2LDRpci:
1407 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1408 NewOpc = ARM::tLDRpci;
1409 Bits = 8;
1410 Scale = 4;
1411 }
1412 break;
1413 }
1414
1415 if (!NewOpc)
1416 continue;
1417
1418 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1419 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1420 // FIXME: Check if offset is multiple of scale if scale is not 4.
1421 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1422 U.MI->setDesc(TII->get(NewOpc));
1423 MachineBasicBlock *MBB = U.MI->getParent();
1424 BBSizes[MBB->getNumber()] -= 2;
1425 AdjustBBOffsetsAfter(MBB, -2);
1426 ++NumT2CPShrunk;
1427 MadeChange = true;
1428 }
1429 }
1430
Evan Chenga1efbbd2009-08-14 00:32:16 +00001431 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001432 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001433 return MadeChange;
1434}
1435
1436bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001437 bool MadeChange = false;
1438
1439 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1440 ImmBranch &Br = ImmBranches[i];
1441 unsigned Opcode = Br.MI->getOpcode();
1442 unsigned NewOpc = 0;
1443 unsigned Scale = 1;
1444 unsigned Bits = 0;
1445 switch (Opcode) {
1446 default: break;
1447 case ARM::t2B:
1448 NewOpc = ARM::tB;
1449 Bits = 11;
1450 Scale = 2;
1451 break;
1452 case ARM::t2Bcc:
1453 NewOpc = ARM::tBcc;
1454 Bits = 8;
1455 Scale = 2;
1456 break;
1457 }
1458 if (!NewOpc)
1459 continue;
1460
1461 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1462 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1463 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1464 Br.MI->setDesc(TII->get(NewOpc));
1465 MachineBasicBlock *MBB = Br.MI->getParent();
1466 BBSizes[MBB->getNumber()] -= 2;
1467 AdjustBBOffsetsAfter(MBB, -2);
1468 ++NumT2BrShrunk;
1469 MadeChange = true;
1470 }
1471 }
1472
1473 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001474}
1475
1476
1477/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1478/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001479bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1480 bool MadeChange = false;
1481
1482 // FIXME: After the tables are shrunk, can we get rid some of the
1483 // constantpool tables?
1484 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1485 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1486 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1487 MachineInstr *MI = T2JumpTables[i];
1488 const TargetInstrDesc &TID = MI->getDesc();
1489 unsigned NumOps = TID.getNumOperands();
1490 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1491 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1492 unsigned JTI = JTOP.getIndex();
1493 assert(JTI < JT.size());
1494
1495 bool ByteOk = true;
1496 bool HalfWordOk = true;
1497 unsigned JTOffset = GetOffsetOf(MI) + 4;
1498 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1499 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1500 MachineBasicBlock *MBB = JTBBs[j];
1501 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001502 // Negative offset is not ok. FIXME: We should change BB layout to make
1503 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001504 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001505 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001506 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001507 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001508 HalfWordOk = false;
1509 if (!ByteOk && !HalfWordOk)
1510 break;
1511 }
1512
1513 if (ByteOk || HalfWordOk) {
1514 MachineBasicBlock *MBB = MI->getParent();
1515 unsigned BaseReg = MI->getOperand(0).getReg();
1516 bool BaseRegKill = MI->getOperand(0).isKill();
1517 if (!BaseRegKill)
1518 continue;
1519 unsigned IdxReg = MI->getOperand(1).getReg();
1520 bool IdxRegKill = MI->getOperand(1).isKill();
1521 MachineBasicBlock::iterator PrevI = MI;
1522 if (PrevI == MBB->begin())
1523 continue;
1524
1525 MachineInstr *AddrMI = --PrevI;
1526 bool OptOk = true;
1527 // Examine the instruction that calculate the jumptable entry address.
1528 // If it's not the one just before the t2BR_JT, we won't delete it, then
1529 // it's not worth doing the optimization.
1530 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1531 const MachineOperand &MO = AddrMI->getOperand(k);
1532 if (!MO.isReg() || !MO.getReg())
1533 continue;
1534 if (MO.isDef() && MO.getReg() != BaseReg) {
1535 OptOk = false;
1536 break;
1537 }
1538 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1539 OptOk = false;
1540 break;
1541 }
1542 }
1543 if (!OptOk)
1544 continue;
1545
Evan Chenga1efbbd2009-08-14 00:32:16 +00001546 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1547 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001548 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001549 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1550 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001551 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001552 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001553
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001554 if (!OptOk)
1555 continue;
1556
1557 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1558 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1559 .addReg(IdxReg, getKillRegState(IdxRegKill))
1560 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1561 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1562 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1563 // is 2-byte aligned. For now, asm printer will fix it up.
1564 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1565 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1566 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1567 OrigSize += TII->GetInstSizeInBytes(MI);
1568
1569 AddrMI->eraseFromParent();
1570 LeaMI->eraseFromParent();
1571 MI->eraseFromParent();
1572
1573 int delta = OrigSize - NewSize;
1574 BBSizes[MBB->getNumber()] -= delta;
1575 AdjustBBOffsetsAfter(MBB, -delta);
1576
1577 ++NumTBs;
1578 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001579 }
1580 }
1581
1582 return MadeChange;
1583}