blob: 9f4de8c7615f93cd373a371fcfe8f23bb3ff606f [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"
Evan Cheng719510a2010-08-12 20:30:05 +000021#include "Thumb2InstrInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000025#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000028#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"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
55namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000056 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000057 /// requires constant pool entries to be scattered among the instructions
58 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000059 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000060 /// special instructions.
61 ///
62 /// The terminology used in this pass includes:
63 /// Islands - Clumps of constants placed in the function.
64 /// Water - Potential places where an island could be formed.
65 /// CPE - A constant pool entry that has been placed somewhere, which
66 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000067 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000068 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000069 /// by MBB Number. The two-byte pads required for Thumb alignment are
70 /// counted as part of the following block (i.e., the offset and size for
71 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000072 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000073
Dale Johannesen99c49a42007-02-25 00:47:03 +000074 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000075 /// The two-byte pads required for Thumb alignment are counted as part of
76 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000077 std::vector<unsigned> BBOffsets;
78
Evan Chenga8e29892007-01-19 07:51:42 +000079 /// WaterList - A sorted list of basic blocks where islands could be placed
80 /// (i.e. blocks that don't fall through to the following block, due
81 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000082 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000083
Bob Wilsonb9239532009-10-15 20:49:47 +000084 /// NewWaterList - The subset of WaterList that was created since the
85 /// previous iteration by inserting unconditional branches.
86 SmallSet<MachineBasicBlock*, 4> NewWaterList;
87
Bob Wilson034de5f2009-10-12 18:52:13 +000088 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
89
Evan Chenga8e29892007-01-19 07:51:42 +000090 /// CPUser - One user of a constant pool, keeping the machine instruction
91 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000092 /// allowed from the instruction to the CP. The HighWaterMark records the
93 /// highest basic block where a new CPEntry can be placed. To ensure this
94 /// pass terminates, the CP entries are initially placed at the end of the
95 /// function and then move monotonically to lower addresses. The
96 /// exception to this rule is when the current CP entry for a particular
97 /// CPUser is out of range, but there is another CP entry for the same
98 /// constant value in range. We want to use the existing in-range CP
99 /// entry, but if it later moves out of range, the search for new water
100 /// should resume where it left off. The HighWaterMark is used to record
101 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000102 struct CPUser {
103 MachineInstr *MI;
104 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000105 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000106 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000107 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000108 bool IsSoImm;
109 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
110 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000111 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
112 HighWaterMark = CPEMI->getParent();
113 }
Evan Chenga8e29892007-01-19 07:51:42 +0000114 };
Bob Wilson84945262009-05-12 17:09:30 +0000115
Evan Chenga8e29892007-01-19 07:51:42 +0000116 /// CPUsers - Keep track of all of the machine instructions that use various
117 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000118 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000119
Evan Chengc99ef082007-02-09 20:54:44 +0000120 /// CPEntry - One per constant pool entry, keeping the machine instruction
121 /// pointer, the constpool index, and the number of CPUser's which
122 /// reference this entry.
123 struct CPEntry {
124 MachineInstr *CPEMI;
125 unsigned CPI;
126 unsigned RefCount;
127 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
128 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
129 };
130
131 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000132 /// instructions. For each original constpool index (i.e. those that
133 /// existed upon entry to this pass), it keeps a vector of entries.
134 /// Original elements are cloned as we go along; the clones are
135 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000136 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000137
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000138 /// ImmBranch - One per immediate branch, keeping the machine instruction
139 /// pointer, conditional or unconditional, the max displacement,
140 /// and (if isCond is true) the corresponding unconditional branch
141 /// opcode.
142 struct ImmBranch {
143 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000144 unsigned MaxDisp : 31;
145 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000146 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000147 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
148 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000149 };
150
Evan Cheng2706f972007-05-16 05:14:06 +0000151 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000152 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000153 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000154
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000155 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
156 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000157 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000158
Evan Cheng5657c012009-07-29 02:18:14 +0000159 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
160 SmallVector<MachineInstr*, 4> T2JumpTables;
161
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000162 /// HasFarJump - True if any far jump instruction has been emitted during
163 /// the branch fix up pass.
164 bool HasFarJump;
165
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000166 /// HasInlineAsm - True if the function contains inline assembly.
167 bool HasInlineAsm;
168
Chris Lattner20628752010-07-22 21:27:00 +0000169 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000170 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000171 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000172 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000173 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000174 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000175 public:
Devang Patel19974732007-05-03 01:11:54 +0000176 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000177 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000178
Evan Cheng5657c012009-07-29 02:18:14 +0000179 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000180
181 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000182 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000183 }
Bob Wilson84945262009-05-12 17:09:30 +0000184
Evan Chenga8e29892007-01-19 07:51:42 +0000185 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000186 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000187 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000188 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000189 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000190 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000191 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000192 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000193 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000194 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000195 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000196 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000197 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000198 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000199 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000200 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000201 void RemoveDeadCPEMI(MachineInstr *CPEMI);
202 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000203 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000204 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
205 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000206 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000207 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000208 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000209 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000210 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000211 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
212 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
213 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000214 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000215 bool OptimizeThumb2Instructions(MachineFunction &MF);
216 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000217 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000218 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000219 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
220 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000221
Evan Chenga8e29892007-01-19 07:51:42 +0000222 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000223 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000224 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000225 };
Devang Patel19974732007-05-03 01:11:54 +0000226 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000227}
228
Dale Johannesen8593e412007-04-29 19:19:30 +0000229/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000230void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000231 assert(BBOffsets.size() == BBSizes.size());
232 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
233 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000234 if (!isThumb)
235 return;
236#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000237 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000238 MBBI != E; ++MBBI) {
239 MachineBasicBlock *MBB = MBBI;
240 if (!MBB->empty() &&
241 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
242 unsigned MBBId = MBB->getNumber();
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000243 assert(HasInlineAsm ||
244 (BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000245 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000246 }
247 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000248 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
249 CPUser &U = CPUsers[i];
250 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000251 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
252 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
253 UserOffset - CPEOffset;
254 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000255 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000256#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000257}
258
259/// print block size and offset information - debugging
260void ARMConstantIslands::dumpBBs() {
261 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000262 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
263 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000264 }
265}
266
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000267/// createARMConstantIslandPass - returns an instance of the constpool
268/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000269FunctionPass *llvm::createARMConstantIslandPass() {
270 return new ARMConstantIslands();
271}
272
Evan Cheng5657c012009-07-29 02:18:14 +0000273bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
274 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000275
Chris Lattner20628752010-07-22 21:27:00 +0000276 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000277 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000278 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
279
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000280 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000281 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000282 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000283
284 HasFarJump = false;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000285 HasInlineAsm = false;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000286
Evan Chenga8e29892007-01-19 07:51:42 +0000287 // Renumber all of the machine basic blocks in the function, guaranteeing that
288 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000289 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000290
Jim Grosbach80697d12009-11-12 17:25:07 +0000291 // Try to reorder and otherwise adjust the block layout to make good use
292 // of the TB[BH] instructions.
293 bool MadeChange = false;
294 if (isThumb2 && AdjustJumpTableBlocks) {
295 JumpTableFunctionScan(MF);
296 MadeChange |= ReorderThumb2JumpTables(MF);
297 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000298 T2JumpTables.clear();
299 // Blocks may have shifted around. Keep the numbering up to date.
300 MF.RenumberBlocks();
301 }
302
Evan Chengd26b14c2009-07-31 18:28:05 +0000303 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000304 // This is so we can keep exact track of where the alignment padding goes.
305
Chris Lattner7d7dab02010-01-27 23:37:36 +0000306 // ARM and Thumb2 functions need to be 4-byte aligned.
307 if (!isThumb1)
308 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000309
Evan Chenga8e29892007-01-19 07:51:42 +0000310 // Perform the initial placement of the constant pool entries. To start with,
311 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000312 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000313 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000314 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000315 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000316 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000317 }
Bob Wilson84945262009-05-12 17:09:30 +0000318
Evan Chenga8e29892007-01-19 07:51:42 +0000319 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000320 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000321
Evan Chenga8e29892007-01-19 07:51:42 +0000322 // Do the initial scan of the function, building up information about the
323 // sizes of each block, the location of all the water, and finding all of the
324 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000325 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000326 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000327 DEBUG(dumpBBs());
328
Bob Wilson84945262009-05-12 17:09:30 +0000329
Evan Chenged884f32007-04-03 23:39:48 +0000330 /// Remove dead constant pool entries.
331 RemoveUnusedCPEntries();
332
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000333 // Iteratively place constant pool entries and fix up branches until there
334 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000335 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000336 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000337 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000338 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000339 CPChange |= HandleConstantPoolUser(MF, i);
340 if (CPChange && ++NoCPIters > 30)
341 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000342 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000343
Bob Wilsonb9239532009-10-15 20:49:47 +0000344 // Clear NewWaterList now. If we split a block for branches, it should
345 // appear as "new water" for the next iteration of constant pool placement.
346 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000347
348 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000349 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000350 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
351 if (BRChange && ++NoBRIters > 30)
352 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000353 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000354
355 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000356 break;
357 MadeChange = true;
358 }
Evan Chenged884f32007-04-03 23:39:48 +0000359
Evan Chenga1efbbd2009-08-14 00:32:16 +0000360 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000361 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000362 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000363
Dale Johannesen8593e412007-04-29 19:19:30 +0000364 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000365 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000366
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000367 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
368 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000369 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000370 MadeChange |= UndoLRSpillRestore();
371
Evan Chengb1c857b2010-07-22 02:09:47 +0000372 DEBUG(errs() << '\n'; dumpBBs());
373
Evan Chenga8e29892007-01-19 07:51:42 +0000374 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000375 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000376 WaterList.clear();
377 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000378 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000379 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000380 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000381 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000382
383 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000384}
385
386/// DoInitialPlacement - Perform the initial placement of the constant pool
387/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000388void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000389 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000390 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000391 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
392 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000393
Evan Chenga8e29892007-01-19 07:51:42 +0000394 // Add all of the constants from the constant pool to the end block, use an
395 // identity mapping of CPI's to CPE's.
396 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000397 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000398
Evan Cheng5657c012009-07-29 02:18:14 +0000399 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000400 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000401 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000402 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
403 // we would have to pad them out or something so that instructions stay
404 // aligned.
405 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
406 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000407 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
408 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000409 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000410
411 // Add a new CPEntry, but no corresponding CPUser yet.
412 std::vector<CPEntry> CPEs;
413 CPEs.push_back(CPEntry(CPEMI, i));
414 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000415 ++NumCPEs;
Chris Lattner893e1c92009-08-23 06:49:22 +0000416 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
417 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000418 }
419}
420
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000421/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000422/// into the block immediately after it.
423static bool BBHasFallthrough(MachineBasicBlock *MBB) {
424 // Get the next machine basic block in the function.
425 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000426 // Can't fall off end of function.
427 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000428 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000429
Chris Lattner7896c9f2009-12-03 00:50:42 +0000430 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000431 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
432 E = MBB->succ_end(); I != E; ++I)
433 if (*I == NextBB)
434 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000435
Evan Chenga8e29892007-01-19 07:51:42 +0000436 return false;
437}
438
Evan Chengc99ef082007-02-09 20:54:44 +0000439/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
440/// look up the corresponding CPEntry.
441ARMConstantIslands::CPEntry
442*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
443 const MachineInstr *CPEMI) {
444 std::vector<CPEntry> &CPEs = CPEntries[CPI];
445 // Number of entries per constpool index should be small, just do a
446 // linear search.
447 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
448 if (CPEs[i].CPEMI == CPEMI)
449 return &CPEs[i];
450 }
451 return NULL;
452}
453
Jim Grosbach80697d12009-11-12 17:25:07 +0000454/// JumpTableFunctionScan - Do a scan of the function, building up
455/// information about the sizes of each block and the locations of all
456/// the jump tables.
457void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000458 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
459 MBBI != E; ++MBBI) {
460 MachineBasicBlock &MBB = *MBBI;
461
Jim Grosbach80697d12009-11-12 17:25:07 +0000462 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000463 I != E; ++I)
464 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
465 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000466 }
467}
468
Evan Chenga8e29892007-01-19 07:51:42 +0000469/// InitialFunctionScan - Do the initial scan of the function, building up
470/// information about the sizes of each block, the location of all the water,
471/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000472void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000473 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000474 // First thing, see if the function has any inline assembly in it. If so,
475 // we have to be conservative about alignment assumptions, as we don't
476 // know for sure the size of any instructions in the inline assembly.
477 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
478 MBBI != E; ++MBBI) {
479 MachineBasicBlock &MBB = *MBBI;
480 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
481 I != E; ++I)
482 if (I->getOpcode() == ARM::INLINEASM)
483 HasInlineAsm = true;
484 }
485
486 // Now go back through the instructions and build up our data structures
Dale Johannesen99c49a42007-02-25 00:47:03 +0000487 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000488 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000489 MBBI != E; ++MBBI) {
490 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000491
Evan Chenga8e29892007-01-19 07:51:42 +0000492 // If this block doesn't fall through into the next MBB, then this is
493 // 'water' that a constant pool island could be placed.
494 if (!BBHasFallthrough(&MBB))
495 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000496
Evan Chenga8e29892007-01-19 07:51:42 +0000497 unsigned MBBSize = 0;
498 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
499 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000500 if (I->isDebugValue())
501 continue;
Evan Chenga8e29892007-01-19 07:51:42 +0000502 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000503 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000504
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000505 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000506 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000507 bool isCond = false;
508 unsigned Bits = 0;
509 unsigned Scale = 1;
510 int UOpc = Opc;
511 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000512 default:
513 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000514 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000515 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000516 // be right, functions containing these must be 4-byte aligned.
Evan Chengb1c857b2010-07-22 02:09:47 +0000517 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
518 // table entries. So this code checks whether offset of tBR_JTr + 2
Dale Johannesen8086d582010-07-23 22:50:23 +0000519 // is aligned. That is held in Offset+MBBSize, which already has
520 // 2 added in for the size of the mov pc instruction.
Chris Lattner7d7dab02010-01-27 23:37:36 +0000521 MF.EnsureAlignment(2U);
Dale Johannesen8086d582010-07-23 22:50:23 +0000522 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
Evan Cheng5657c012009-07-29 02:18:14 +0000523 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000524 MBBSize += 2; // padding
525 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000526 case ARM::t2BR_JT:
527 T2JumpTables.push_back(I);
528 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000529 case ARM::Bcc:
530 isCond = true;
531 UOpc = ARM::B;
532 // Fallthrough
533 case ARM::B:
534 Bits = 24;
535 Scale = 4;
536 break;
537 case ARM::tBcc:
538 isCond = true;
539 UOpc = ARM::tB;
540 Bits = 8;
541 Scale = 2;
542 break;
543 case ARM::tB:
544 Bits = 11;
545 Scale = 2;
546 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000547 case ARM::t2Bcc:
548 isCond = true;
549 UOpc = ARM::t2B;
550 Bits = 20;
551 Scale = 2;
552 break;
553 case ARM::t2B:
554 Bits = 24;
555 Scale = 2;
556 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000557 }
Evan Chengb43216e2007-02-01 10:16:15 +0000558
559 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000560 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000561 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000562 }
563
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000564 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
565 PushPopMIs.push_back(I);
566
Evan Chengd3d9d662009-07-23 18:27:47 +0000567 if (Opc == ARM::CONSTPOOL_ENTRY)
568 continue;
569
Evan Chenga8e29892007-01-19 07:51:42 +0000570 // Scan the instructions for constant pool operands.
571 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000572 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000573 // We found one. The addressing mode tells us the max displacement
574 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000575
Evan Chenga8e29892007-01-19 07:51:42 +0000576 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000577 unsigned Bits = 0;
578 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000579 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000580 bool IsSoImm = false;
581
582 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000583 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000584 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000585 break;
586
587 // Taking the address of a CP entry.
588 case ARM::LEApcrel:
589 // This takes a SoImm, which is 8 bit immediate rotated. We'll
590 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000591 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000592 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000593 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000594 Scale = 4;
595 NegOk = true;
596 IsSoImm = true;
597 break;
598 case ARM::t2LEApcrel:
599 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000600 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000601 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000602 case ARM::tLEApcrel:
603 Bits = 8;
604 Scale = 4;
605 break;
606
607 case ARM::LDR:
608 case ARM::LDRcp:
609 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000610 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000611 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000612 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000613
614 case ARM::tLDRpci:
615 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000616 Bits = 8;
617 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000618 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000619
Jim Grosbache5165492009-11-09 00:11:35 +0000620 case ARM::VLDRD:
621 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000622 Bits = 8;
623 Scale = 4; // +-(offset_8*4)
624 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000625 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000626 }
Evan Chengb43216e2007-02-01 10:16:15 +0000627
Evan Chenga8e29892007-01-19 07:51:42 +0000628 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000629 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000630 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000631 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000632 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000633
634 // Increment corresponding CPEntry reference count.
635 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
636 assert(CPE && "Cannot find a corresponding CPEntry!");
637 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000638
Evan Chenga8e29892007-01-19 07:51:42 +0000639 // Instructions can only use one CP entry, don't bother scanning the
640 // rest of the operands.
641 break;
642 }
643 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000644
Dale Johannesen8593e412007-04-29 19:19:30 +0000645 // In thumb mode, if this block is a constpool island, we may need padding
646 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000647 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000648 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000649 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000650 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000651 MBBSize += 2;
652
Evan Chenga8e29892007-01-19 07:51:42 +0000653 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000654 BBOffsets.push_back(Offset);
655 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000656 }
657}
658
Evan Chenga8e29892007-01-19 07:51:42 +0000659/// GetOffsetOf - Return the current offset of the specified machine instruction
660/// from the start of the function. This offset changes as stuff is moved
661/// around inside the function.
662unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
663 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000664
Evan Chenga8e29892007-01-19 07:51:42 +0000665 // The offset is composed of two things: the sum of the sizes of all MBB's
666 // before this instruction's block, and the offset from the start of the block
667 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000668 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000669
Dale Johannesen8593e412007-04-29 19:19:30 +0000670 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
671 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000672 if (isThumb &&
673 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000674 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000675 Offset += 2;
676
Evan Chenga8e29892007-01-19 07:51:42 +0000677 // Sum instructions before MI in MBB.
678 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
679 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
680 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000681 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000682 }
683}
684
685/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
686/// ID.
687static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
688 const MachineBasicBlock *RHS) {
689 return LHS->getNumber() < RHS->getNumber();
690}
691
692/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
693/// machine function, it upsets all of the block numbers. Renumber the blocks
694/// and update the arrays that parallel this numbering.
695void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
696 // Renumber the MBB's to keep them consequtive.
697 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000698
Evan Chenga8e29892007-01-19 07:51:42 +0000699 // Insert a size into BBSizes to align it properly with the (newly
700 // renumbered) block numbers.
701 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000702
703 // Likewise for BBOffsets.
704 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000705
706 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000707 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000708 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000709 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
710 CompareMBBNumbers);
711 WaterList.insert(IP, NewBB);
712}
713
714
715/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000716/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000717/// account for this change and returns the newly created block.
718MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000719 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000720 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000721
722 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000723 MachineBasicBlock *NewBB =
724 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000725 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000726 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000727
Evan Chenga8e29892007-01-19 07:51:42 +0000728 // Splice the instructions starting with MI over to NewBB.
729 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000730
Evan Chenga8e29892007-01-19 07:51:42 +0000731 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000732 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000733 // There doesn't seem to be meaningful DebugInfo available; this doesn't
734 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000735 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000736 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanfe601042010-06-22 15:08:57 +0000737 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000738
Evan Chenga8e29892007-01-19 07:51:42 +0000739 // Update the CFG. All succs of OrigBB are now succs of NewBB.
740 while (!OrigBB->succ_empty()) {
741 MachineBasicBlock *Succ = *OrigBB->succ_begin();
742 OrigBB->removeSuccessor(Succ);
743 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000744
Evan Chenga8e29892007-01-19 07:51:42 +0000745 // This pass should be run after register allocation, so there should be no
746 // PHI nodes to update.
Chris Lattner518bb532010-02-09 19:54:29 +0000747 assert((Succ->empty() || !Succ->begin()->isPHI())
Evan Chenga8e29892007-01-19 07:51:42 +0000748 && "PHI nodes should be eliminated by now!");
749 }
Bob Wilson84945262009-05-12 17:09:30 +0000750
Evan Chenga8e29892007-01-19 07:51:42 +0000751 // OrigBB branches to NewBB.
752 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000753
Evan Chenga8e29892007-01-19 07:51:42 +0000754 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000755 // This is almost the same as UpdateForInsertedWaterBlock, except that
756 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000757 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000758
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000759 // Insert a size into BBSizes to align it properly with the (newly
760 // renumbered) block numbers.
761 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000762
Dale Johannesen99c49a42007-02-25 00:47:03 +0000763 // Likewise for BBOffsets.
764 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
765
Bob Wilson84945262009-05-12 17:09:30 +0000766 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000767 // available water after it (but not if it's already there, which happens
768 // when splitting before a conditional branch that is followed by an
769 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000770 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000771 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
772 CompareMBBNumbers);
773 MachineBasicBlock* WaterBB = *IP;
774 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000775 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000776 else
777 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000778 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000779
Dale Johannesen99c49a42007-02-25 00:47:03 +0000780 unsigned OrigBBI = OrigBB->getNumber();
781 unsigned NewBBI = NewBB->getNumber();
Bob Wilson84945262009-05-12 17:09:30 +0000782
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000783 int delta = isThumb1 ? 2 : 4;
Dale Johannesen8086d582010-07-23 22:50:23 +0000784
785 // Figure out how large the OrigBB is. As the first half of the original
786 // block, it cannot contain a tablejump. The size includes
787 // the new jump we added. (It should be possible to do this without
788 // recounting everything, but it's very confusing, and this is rarely
789 // executed.)
790 unsigned OrigBBSize = 0;
791 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
792 I != E; ++I)
793 OrigBBSize += TII->GetInstSizeInBytes(I);
794 BBSizes[OrigBBI] = OrigBBSize;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000795
796 // ...and adjust BBOffsets for NewBB accordingly.
797 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
798
Dale Johannesen8086d582010-07-23 22:50:23 +0000799 // Figure out how large the NewMBB is. As the second half of the original
800 // block, it may contain a tablejump.
801 unsigned NewBBSize = 0;
802 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
803 I != E; ++I)
804 NewBBSize += TII->GetInstSizeInBytes(I);
805 // Set the size of NewBB in BBSizes. It does not include any padding now.
806 BBSizes[NewBBI] = NewBBSize;
807
808 MachineInstr* ThumbJTMI = prior(NewBB->end());
809 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
810 // We've added another 2-byte instruction before this tablejump, which
811 // means we will always need padding if we didn't before, and vice versa.
812
813 // The original offset of the jump instruction was:
814 unsigned OrigOffset = BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
815 if (OrigOffset%4 == 0) {
816 // We had padding before and now we don't. No net change in code size.
817 delta = 0;
818 } else {
819 // We didn't have padding before and now we do.
820 BBSizes[NewBBI] += 2;
821 delta = 4;
822 }
823 }
824
Dale Johannesen99c49a42007-02-25 00:47:03 +0000825 // All BBOffsets following these blocks must be modified.
Dale Johannesen8086d582010-07-23 22:50:23 +0000826 if (delta)
827 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000828
829 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000830}
831
Dale Johannesen8593e412007-04-29 19:19:30 +0000832/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000833/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000834/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000835bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000836 unsigned TrialOffset, unsigned MaxDisp,
837 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000838 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
839 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000840 // Effectively, the valid range of displacements is 2 bytes smaller for such
841 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000842 unsigned TotalAdj = 0;
843 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000844 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000845 TotalAdj = 2;
846 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000847 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000848 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000849 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000850 TotalAdj += 2;
851 }
852
853 // In Thumb2 mode, later branch adjustments can shift instructions up and
854 // cause alignment change. In the worst case scenario this can cause the
855 // user's effective address to be subtracted by 2 and the CPE's address to
856 // be plus 2.
857 if (isThumb2 && TotalAdj != 4)
858 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000859
Dale Johannesen99c49a42007-02-25 00:47:03 +0000860 if (UserOffset <= TrialOffset) {
861 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000862 if (TrialOffset - UserOffset <= MaxDisp)
863 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000864 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000865 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000866 if (UserOffset - TrialOffset <= MaxDisp)
867 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000868 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000869 }
870 return false;
871}
872
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000873/// WaterIsInRange - Returns true if a CPE placed after the specified
874/// Water (a basic block) will be in range for the specific MI.
875
876bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000877 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000878 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000879 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000880 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881
Dale Johannesend959aa42007-04-02 20:31:06 +0000882 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000883 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000884 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000885 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000886
Evan Chengd3d9d662009-07-23 18:27:47 +0000887 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888}
889
890/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000891/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000892bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000893 MachineInstr *CPEMI, unsigned MaxDisp,
894 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000895 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000896 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000897
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000899 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
900 << " max delta=" << MaxDisp
901 << " insn address=" << UserOffset
902 << " CPE address=" << CPEOffset
903 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000904 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000905
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000906 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000907}
908
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000909#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000910/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
911/// unconditionally branches to its only successor.
912static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
913 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
914 return false;
915
916 MachineBasicBlock *Succ = *MBB->succ_begin();
917 MachineBasicBlock *Pred = *MBB->pred_begin();
918 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000919 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
920 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000921 return PredMI->getOperand(0).getMBB() == Succ;
922 return false;
923}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000924#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000925
Bob Wilson84945262009-05-12 17:09:30 +0000926void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000927 int delta) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000928 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000929 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
930 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000931 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000932 // If some existing blocks have padding, adjust the padding as needed, a
933 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000934 if (!isThumb)
935 continue;
936 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000937 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000938 // Constant pool entries require padding.
939 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000940 unsigned OldOffset = BBOffsets[i] - delta;
941 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000942 // add new padding
943 BBSizes[i] += 2;
944 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000945 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000946 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000947 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000948 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000950 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000951 // Thumb1 jump tables require padding. They should be at the end;
952 // following unconditional branches are removed by AnalyzeBranch.
Evan Chengb1c857b2010-07-22 02:09:47 +0000953 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
Dale Johannesen8086d582010-07-23 22:50:23 +0000954 // table entries. So this code checks whether offset of tBR_JTr
955 // is aligned; if it is, the offset of the jump table following the
956 // instruction will not be aligned, and we need padding.
Evan Cheng78947622009-07-24 18:20:44 +0000957 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000958 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Dale Johannesen8086d582010-07-23 22:50:23 +0000959 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
Evan Cheng4a8ea212009-08-11 07:36:14 +0000960 unsigned OldMIOffset = NewMIOffset - delta;
961 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000962 // remove existing padding
963 BBSizes[i] -= 2;
964 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000965 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000966 // add new padding
967 BBSizes[i] += 2;
968 delta += 2;
969 }
970 }
971 if (delta==0)
972 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000973 }
Chris Lattner7896c9f2009-12-03 00:50:42 +0000974 MBBI = llvm::next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000975 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000976}
977
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000978/// DecrementOldEntry - find the constant pool entry with index CPI
979/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000980/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000981/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000982
Evan Chenged884f32007-04-03 23:39:48 +0000983bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000984 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000985 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
986 assert(CPE && "Unexpected!");
987 if (--CPE->RefCount == 0) {
988 RemoveDeadCPEMI(CPEMI);
989 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000990 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000991 return true;
992 }
993 return false;
994}
995
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000996/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
997/// if not, see if an in-range clone of the CPE is in range, and if so,
998/// change the data structures so the user references the clone. Returns:
999/// 0 = no existing entry found
1000/// 1 = entry found, and there were no code insertions or deletions
1001/// 2 = entry found, and there were code insertions or deletions
1002int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1003{
1004 MachineInstr *UserMI = U.MI;
1005 MachineInstr *CPEMI = U.CPEMI;
1006
1007 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001008 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001009 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001010 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001011 }
1012
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001013 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001014 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001015 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1016 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1017 // We already tried this one
1018 if (CPEs[i].CPEMI == CPEMI)
1019 continue;
1020 // Removing CPEs can leave empty entries, skip
1021 if (CPEs[i].CPEMI == NULL)
1022 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001023 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001024 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1025 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001026 // Point the CPUser node to the replacement
1027 U.CPEMI = CPEs[i].CPEMI;
1028 // Change the CPI in the instruction operand to refer to the clone.
1029 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001030 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001031 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032 break;
1033 }
1034 // Adjust the refcount of the clone...
1035 CPEs[i].RefCount++;
1036 // ...and the original. If we didn't remove the old entry, none of the
1037 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001038 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001039 }
1040 }
1041 return 0;
1042}
1043
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001044/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1045/// the specific unconditional branch instruction.
1046static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001047 switch (Opc) {
1048 case ARM::tB:
1049 return ((1<<10)-1)*2;
1050 case ARM::t2B:
1051 return ((1<<23)-1)*2;
1052 default:
1053 break;
1054 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001055
David Goodwin5e47a9a2009-06-30 18:04:13 +00001056 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001057}
1058
Bob Wilsonb9239532009-10-15 20:49:47 +00001059/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001060/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001061/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001062/// is set to the WaterList entry. For Thumb, prefer water that will not
1063/// introduce padding to water that will. To ensure that this pass
1064/// terminates, the CPE location for a particular CPUser is only allowed to
1065/// move to a lower address, so search backward from the end of the list and
1066/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001067bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001068 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001069 if (WaterList.empty())
1070 return false;
1071
Bob Wilson32c50e82009-10-12 20:45:53 +00001072 bool FoundWaterThatWouldPad = false;
1073 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001074 for (water_iterator IP = prior(WaterList.end()),
1075 B = WaterList.begin();; --IP) {
1076 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001077 // Check if water is in range and is either at a lower address than the
1078 // current "high water mark" or a new water block that was created since
1079 // the previous iteration by inserting an unconditional branch. In the
1080 // latter case, we want to allow resetting the high water mark back to
1081 // this new water since we haven't seen it before. Inserting branches
1082 // should be relatively uncommon and when it does happen, we want to be
1083 // sure to take advantage of it for all the CPEs near that block, so that
1084 // we don't insert more branches than necessary.
1085 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1086 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1087 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001088 unsigned WBBId = WaterBB->getNumber();
1089 if (isThumb &&
1090 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1091 // This is valid Water, but would introduce padding. Remember
1092 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001093 if (!FoundWaterThatWouldPad) {
1094 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001095 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001096 }
Bob Wilson3b757352009-10-12 19:04:03 +00001097 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001098 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001099 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001100 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001101 }
Bob Wilson3b757352009-10-12 19:04:03 +00001102 if (IP == B)
1103 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001105 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001106 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001107 return true;
1108 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001109 return false;
1110}
1111
Bob Wilson84945262009-05-12 17:09:30 +00001112/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001113/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1114/// block is used if in range, and the conditional branch munged so control
1115/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001116/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001117/// block following which the new island can be inserted (the WaterList
1118/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001119void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001120 unsigned UserOffset,
1121 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001122 CPUser &U = CPUsers[CPUserIndex];
1123 MachineInstr *UserMI = U.MI;
1124 MachineInstr *CPEMI = U.CPEMI;
1125 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001126 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001127 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001128 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001129
Bob Wilson36fa5322009-10-15 05:10:36 +00001130 // If the block does not end in an unconditional branch already, and if the
1131 // end of the block is within range, make new water there. (The addition
1132 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1133 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001134 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001135 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001136 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1137 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001138 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001139 if (&UserMBB->back() == UserMI)
1140 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001141 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001142 // Add an unconditional branch from UserMBB to fallthrough block.
1143 // Record it for branch lengthening; this new branch will not get out of
1144 // range, but if the preceding conditional branch is out of range, the
1145 // targets will be exchanged, and the altered branch may be out of
1146 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001147 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001148 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001149 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001150 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001151 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001152 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001153 BBSizes[UserMBB->getNumber()] += delta;
1154 AdjustBBOffsetsAfter(UserMBB, delta);
1155 } else {
1156 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001157 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001158 // and constant pool entries are 4 bytes: if instruction I references
1159 // island CPE, and instruction I+1 references CPE', it will
1160 // not work well to put CPE as far forward as possible, since then
1161 // CPE' cannot immediately follow it (that location is 2 bytes
1162 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001163 // a new island. So, we make a first guess, then walk through the
1164 // instructions between the one currently being looked at and the
1165 // possible insertion point, and make sure any other instructions
1166 // that reference CPEs will be able to use the same island area;
1167 // if not, we back up the insertion point.
1168
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001169 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001170 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001171 // island is handled inside OffsetIsInRange.
1172 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001173 // This could point off the end of the block if we've already got
1174 // constant pool entries following this block; only the last one is
1175 // in the water list. Back past any possible branches (allow for a
1176 // conditional and a maximally long unconditional).
1177 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001178 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001179 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001180 unsigned EndInsertOffset = BaseInsertOffset +
1181 CPEMI->getOperand(2).getImm();
1182 MachineBasicBlock::iterator MI = UserMI;
1183 ++MI;
1184 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001185 unsigned NumCPUsers = CPUsers.size();
1186 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001187 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001188 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001189 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001190 MI = llvm::next(MI)) {
1191 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001192 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001193 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001194 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1195 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1196 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001197 }
1198 // This is overly conservative, as we don't account for CPEMIs
1199 // being reused within the block, but it doesn't matter much.
1200 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1201 CPUIndex++;
1202 }
Evan Cheng719510a2010-08-12 20:30:05 +00001203
1204 // Remember the last IT instruction.
1205 if (MI->getOpcode() == ARM::t2IT)
1206 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001207 }
Evan Cheng719510a2010-08-12 20:30:05 +00001208
Chris Lattner893e1c92009-08-23 06:49:22 +00001209 DEBUG(errs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001210 --MI;
1211
1212 // Avoid splitting an IT block.
1213 if (LastIT) {
1214 unsigned PredReg = 0;
1215 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1216 if (CC != ARMCC::AL)
1217 MI = LastIT;
1218 }
1219 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001220 }
1221}
1222
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001224/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001225/// place in-range. Return true if we changed any addresses (thus must run
1226/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001227bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001228 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001229 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001230 MachineInstr *UserMI = U.MI;
1231 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001232 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001233 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001234 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001235 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001236 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001237
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001238 // See if the current entry is within range, or there is a clone of it
1239 // in range.
1240 int result = LookForExistingCPEntry(U, UserOffset);
1241 if (result==1) return false;
1242 else if (result==2) return true;
1243
1244 // No existing clone of this CPE is within range.
1245 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001246 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001247
Bob Wilsonf98032e2009-10-12 21:23:15 +00001248 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001249 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1250 MachineBasicBlock *NewMBB;
1251 water_iterator IP;
1252 if (LookForWater(U, UserOffset, IP)) {
1253 DEBUG(errs() << "found water in range\n");
1254 MachineBasicBlock *WaterBB = *IP;
1255
1256 // If the original WaterList entry was "new water" on this iteration,
1257 // propagate that to the new island. This is just keeping NewWaterList
1258 // updated to match the WaterList, which will be updated below.
1259 if (NewWaterList.count(WaterBB)) {
1260 NewWaterList.erase(WaterBB);
1261 NewWaterList.insert(NewIsland);
1262 }
1263 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001264 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001265
1266 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001267 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001268 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001269 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001270
1271 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1272 // called while handling branches so that the water will be seen on the
1273 // next iteration for constant pools, but in this context, we don't want
1274 // it. Check for this so it will be removed from the WaterList.
1275 // Also remove any entry from NewWaterList.
1276 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1277 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1278 if (IP != WaterList.end())
1279 NewWaterList.erase(WaterBB);
1280
1281 // We are adding new water. Update NewWaterList.
1282 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001283 }
1284
Bob Wilsonb9239532009-10-15 20:49:47 +00001285 // Remove the original WaterList entry; we want subsequent insertions in
1286 // this vicinity to go after the one we're about to insert. This
1287 // considerably reduces the number of times we have to move the same CPE
1288 // more than once and is also important to ensure the algorithm terminates.
1289 if (IP != WaterList.end())
1290 WaterList.erase(IP);
1291
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001292 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001293 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001294
1295 // Update internal data structures to account for the newly inserted MBB.
1296 UpdateForInsertedWaterBlock(NewIsland);
1297
1298 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001299 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001300
1301 // Now that we have an island to add the CPE to, clone the original CPE and
1302 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001303 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001304 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001305 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001306 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001307 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001308
Dale Johannesen8593e412007-04-29 19:19:30 +00001309 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001310 // Compensate for .align 2 in thumb mode.
Jim Grosbach4d8e90a2009-11-19 23:10:28 +00001311 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001312 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001313 // Increase the size of the island block to account for the new entry.
1314 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001315 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001316
Evan Chenga8e29892007-01-19 07:51:42 +00001317 // Finally, change the CPI in the instruction operand to be ID.
1318 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001319 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001320 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001321 break;
1322 }
Bob Wilson84945262009-05-12 17:09:30 +00001323
Chris Lattner705e07f2009-08-23 03:41:05 +00001324 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1325 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001326
Evan Chenga8e29892007-01-19 07:51:42 +00001327 return true;
1328}
1329
Evan Chenged884f32007-04-03 23:39:48 +00001330/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1331/// sizes and offsets of impacted basic blocks.
1332void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1333 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001334 unsigned Size = CPEMI->getOperand(2).getImm();
1335 CPEMI->eraseFromParent();
1336 BBSizes[CPEBB->getNumber()] -= Size;
1337 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001338 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001339 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001340 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001341 // empty, so fix this.
1342 // All succeeding offsets have the current size value added in, fix this.
1343 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001344 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001345 BBSizes[CPEBB->getNumber()] = 0;
1346 }
Evan Chenged884f32007-04-03 23:39:48 +00001347 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001348 AdjustBBOffsetsAfter(CPEBB, -Size);
1349 // An island has only one predecessor BB and one successor BB. Check if
1350 // this BB's predecessor jumps directly to this BB's successor. This
1351 // shouldn't happen currently.
1352 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1353 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001354}
1355
1356/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1357/// are zero.
1358bool ARMConstantIslands::RemoveUnusedCPEntries() {
1359 unsigned MadeChange = false;
1360 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1361 std::vector<CPEntry> &CPEs = CPEntries[i];
1362 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1363 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1364 RemoveDeadCPEMI(CPEs[j].CPEMI);
1365 CPEs[j].CPEMI = NULL;
1366 MadeChange = true;
1367 }
1368 }
Bob Wilson84945262009-05-12 17:09:30 +00001369 }
Evan Chenged884f32007-04-03 23:39:48 +00001370 return MadeChange;
1371}
1372
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001374/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001375bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1376 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001377 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001378 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001379 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001380
Chris Lattner705e07f2009-08-23 03:41:05 +00001381 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1382 << " from BB#" << MI->getParent()->getNumber()
1383 << " max delta=" << MaxDisp
1384 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1385 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001386
Dale Johannesen8593e412007-04-29 19:19:30 +00001387 if (BrOffset <= DestOffset) {
1388 // Branch before the Dest.
1389 if (DestOffset-BrOffset <= MaxDisp)
1390 return true;
1391 } else {
1392 if (BrOffset-DestOffset <= MaxDisp)
1393 return true;
1394 }
1395 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001396}
1397
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001398/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1399/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001400bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001401 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001402 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001403
Evan Chengc0dbec72007-01-31 19:57:44 +00001404 // Check to see if the DestBB is already in-range.
1405 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001406 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001407
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001408 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001409 return FixUpUnconditionalBr(MF, Br);
1410 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001411}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001412
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001413/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1414/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001415/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001416/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001417bool
Evan Cheng5657c012009-07-29 02:18:14 +00001418ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001419 MachineInstr *MI = Br.MI;
1420 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001421 if (!isThumb1)
1422 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001423
1424 // Use BL to implement far jump.
1425 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001426 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001427 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001428 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001429 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001430 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001431
Chris Lattner705e07f2009-08-23 03:41:05 +00001432 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001433
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001434 return true;
1435}
1436
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001437/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001438/// far away to fit in its displacement field. It is converted to an inverse
1439/// conditional branch + an unconditional branch to the destination.
1440bool
Evan Cheng5657c012009-07-29 02:18:14 +00001441ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001442 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001443 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001444
Bob Wilson39bf0512009-05-12 17:35:29 +00001445 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001446 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001447 // blt L1
1448 // =>
1449 // bge L2
1450 // b L1
1451 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001452 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001453 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001454 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001455
1456 // If the branch is at the end of its MBB and that has a fall-through block,
1457 // direct the updated conditional branch to the fall-through block. Otherwise,
1458 // split the MBB before the next instruction.
1459 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001460 MachineInstr *BMI = &MBB->back();
1461 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001462
Dan Gohmanfe601042010-06-22 15:08:57 +00001463 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001464 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001465 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001466 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001467 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001468 // condition and swap destinations:
1469 // beq L1
1470 // b L2
1471 // =>
1472 // bne L2
1473 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001474 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001475 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001476 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1477 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001478 BMI->getOperand(0).setMBB(DestBB);
1479 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001480 MI->getOperand(1).setImm(CC);
1481 return true;
1482 }
1483 }
1484 }
1485
1486 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001487 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001488 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001489 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001490 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001491 BBSizes[MBB->getNumber()] -= delta;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001492 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
Dale Johannesen8593e412007-04-29 19:19:30 +00001493 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001494 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001495 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001496 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001497 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001498
Chris Lattner893e1c92009-08-23 06:49:22 +00001499 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1500 << " also invert condition and change dest. to BB#"
1501 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001502
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001503 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001504 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001505 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001506 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001507 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001508 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001509 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001510 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001511 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001512 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001513
1514 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001515 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001516 MI->eraseFromParent();
1517
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001518 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001519 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001520 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001521 return true;
1522}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001523
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001524/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001525/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1526/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001527bool ARMConstantIslands::UndoLRSpillRestore() {
1528 bool MadeChange = false;
1529 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1530 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001531 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001532 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001533 MI->getOperand(2).getReg() == ARM::PC &&
1534 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001535 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001536 MI->eraseFromParent();
1537 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001538 }
1539 }
1540 return MadeChange;
1541}
Evan Cheng5657c012009-07-29 02:18:14 +00001542
Evan Chenga1efbbd2009-08-14 00:32:16 +00001543bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1544 bool MadeChange = false;
1545
1546 // Shrink ADR and LDR from constantpool.
1547 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1548 CPUser &U = CPUsers[i];
1549 unsigned Opcode = U.MI->getOpcode();
1550 unsigned NewOpc = 0;
1551 unsigned Scale = 1;
1552 unsigned Bits = 0;
1553 switch (Opcode) {
1554 default: break;
1555 case ARM::t2LEApcrel:
1556 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1557 NewOpc = ARM::tLEApcrel;
1558 Bits = 8;
1559 Scale = 4;
1560 }
1561 break;
1562 case ARM::t2LDRpci:
1563 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1564 NewOpc = ARM::tLDRpci;
1565 Bits = 8;
1566 Scale = 4;
1567 }
1568 break;
1569 }
1570
1571 if (!NewOpc)
1572 continue;
1573
1574 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1575 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1576 // FIXME: Check if offset is multiple of scale if scale is not 4.
1577 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1578 U.MI->setDesc(TII->get(NewOpc));
1579 MachineBasicBlock *MBB = U.MI->getParent();
1580 BBSizes[MBB->getNumber()] -= 2;
1581 AdjustBBOffsetsAfter(MBB, -2);
1582 ++NumT2CPShrunk;
1583 MadeChange = true;
1584 }
1585 }
1586
Evan Chenga1efbbd2009-08-14 00:32:16 +00001587 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001588 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001589 return MadeChange;
1590}
1591
1592bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001593 bool MadeChange = false;
1594
1595 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1596 ImmBranch &Br = ImmBranches[i];
1597 unsigned Opcode = Br.MI->getOpcode();
1598 unsigned NewOpc = 0;
1599 unsigned Scale = 1;
1600 unsigned Bits = 0;
1601 switch (Opcode) {
1602 default: break;
1603 case ARM::t2B:
1604 NewOpc = ARM::tB;
1605 Bits = 11;
1606 Scale = 2;
1607 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001608 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001609 NewOpc = ARM::tBcc;
1610 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001611 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001612 break;
1613 }
Evan Chengde17fb62009-10-31 23:46:45 +00001614 }
1615 if (NewOpc) {
1616 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1617 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1618 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1619 Br.MI->setDesc(TII->get(NewOpc));
1620 MachineBasicBlock *MBB = Br.MI->getParent();
1621 BBSizes[MBB->getNumber()] -= 2;
1622 AdjustBBOffsetsAfter(MBB, -2);
1623 ++NumT2BrShrunk;
1624 MadeChange = true;
1625 }
1626 }
1627
1628 Opcode = Br.MI->getOpcode();
1629 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001630 continue;
1631
Evan Chengde17fb62009-10-31 23:46:45 +00001632 NewOpc = 0;
1633 unsigned PredReg = 0;
1634 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1635 if (Pred == ARMCC::EQ)
1636 NewOpc = ARM::tCBZ;
1637 else if (Pred == ARMCC::NE)
1638 NewOpc = ARM::tCBNZ;
1639 if (!NewOpc)
1640 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001641 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001642 // Check if the distance is within 126. Subtract starting offset by 2
1643 // because the cmp will be eliminated.
1644 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1645 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1646 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1647 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1648 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1649 unsigned Reg = CmpMI->getOperand(0).getReg();
1650 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1651 if (Pred == ARMCC::AL &&
1652 CmpMI->getOperand(1).getImm() == 0 &&
1653 isARMLowRegister(Reg)) {
1654 MachineBasicBlock *MBB = Br.MI->getParent();
1655 MachineInstr *NewBR =
1656 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1657 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1658 CmpMI->eraseFromParent();
1659 Br.MI->eraseFromParent();
1660 Br.MI = NewBR;
1661 BBSizes[MBB->getNumber()] -= 2;
1662 AdjustBBOffsetsAfter(MBB, -2);
1663 ++NumCBZ;
1664 MadeChange = true;
1665 }
1666 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001667 }
1668 }
1669
1670 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001671}
1672
Evan Chenga1efbbd2009-08-14 00:32:16 +00001673/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1674/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001675bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1676 bool MadeChange = false;
1677
1678 // FIXME: After the tables are shrunk, can we get rid some of the
1679 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001680 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001681 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001682
Evan Cheng5657c012009-07-29 02:18:14 +00001683 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1684 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1685 MachineInstr *MI = T2JumpTables[i];
1686 const TargetInstrDesc &TID = MI->getDesc();
1687 unsigned NumOps = TID.getNumOperands();
1688 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1689 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1690 unsigned JTI = JTOP.getIndex();
1691 assert(JTI < JT.size());
1692
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001693 bool ByteOk = true;
1694 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001695 unsigned JTOffset = GetOffsetOf(MI) + 4;
1696 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001697 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1698 MachineBasicBlock *MBB = JTBBs[j];
1699 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001700 // Negative offset is not ok. FIXME: We should change BB layout to make
1701 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001702 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001703 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001704 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001705 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001706 HalfWordOk = false;
1707 if (!ByteOk && !HalfWordOk)
1708 break;
1709 }
1710
1711 if (ByteOk || HalfWordOk) {
1712 MachineBasicBlock *MBB = MI->getParent();
1713 unsigned BaseReg = MI->getOperand(0).getReg();
1714 bool BaseRegKill = MI->getOperand(0).isKill();
1715 if (!BaseRegKill)
1716 continue;
1717 unsigned IdxReg = MI->getOperand(1).getReg();
1718 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001719
1720 // Scan backwards to find the instruction that defines the base
1721 // register. Due to post-RA scheduling, we can't count on it
1722 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001723 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001724 MachineBasicBlock::iterator B = MBB->begin();
1725 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1726 --PrevI;
1727
1728 // If for some reason we didn't find it, we can't do anything, so
1729 // just skip this one.
1730 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001731 continue;
1732
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001733 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001734 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001735 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001736 // Make sure it only defines the base register and kills any uses
1737 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001738 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1739 const MachineOperand &MO = AddrMI->getOperand(k);
1740 if (!MO.isReg() || !MO.getReg())
1741 continue;
1742 if (MO.isDef() && MO.getReg() != BaseReg) {
1743 OptOk = false;
1744 break;
1745 }
1746 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1747 OptOk = false;
1748 break;
1749 }
1750 }
1751 if (!OptOk)
1752 continue;
1753
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001754 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1755 // that gave us the initial base register definition.
1756 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1757 ;
1758
1759 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001760 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001761 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001762 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1763 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001764 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001765 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001766
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001767 if (!OptOk)
1768 continue;
1769
1770 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1771 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1772 .addReg(IdxReg, getKillRegState(IdxRegKill))
1773 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1774 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1775 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1776 // is 2-byte aligned. For now, asm printer will fix it up.
1777 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1778 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1779 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1780 OrigSize += TII->GetInstSizeInBytes(MI);
1781
1782 AddrMI->eraseFromParent();
1783 LeaMI->eraseFromParent();
1784 MI->eraseFromParent();
1785
1786 int delta = OrigSize - NewSize;
1787 BBSizes[MBB->getNumber()] -= delta;
1788 AdjustBBOffsetsAfter(MBB, -delta);
1789
1790 ++NumTBs;
1791 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001792 }
1793 }
1794
1795 return MadeChange;
1796}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001797
Jim Grosbach9249efe2009-11-16 18:55:47 +00001798/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1799/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001800bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1801 bool MadeChange = false;
1802
1803 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001804 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001805
Jim Grosbach80697d12009-11-12 17:25:07 +00001806 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1807 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1808 MachineInstr *MI = T2JumpTables[i];
1809 const TargetInstrDesc &TID = MI->getDesc();
1810 unsigned NumOps = TID.getNumOperands();
1811 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1812 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1813 unsigned JTI = JTOP.getIndex();
1814 assert(JTI < JT.size());
1815
1816 // We prefer if target blocks for the jump table come after the jump
1817 // instruction so we can use TB[BH]. Loop through the target blocks
1818 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001819 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001820 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1821 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1822 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001823 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001824
Jim Grosbach08cbda52009-11-16 18:58:52 +00001825 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001826 // The destination precedes the switch. Try to move the block forward
1827 // so we have a positive offset.
1828 MachineBasicBlock *NewBB =
1829 AdjustJTTargetBlockForward(MBB, MI->getParent());
1830 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001831 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001832 MadeChange = true;
1833 }
1834 }
1835 }
1836
1837 return MadeChange;
1838}
1839
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001840MachineBasicBlock *ARMConstantIslands::
1841AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1842{
1843 MachineFunction &MF = *BB->getParent();
1844
Jim Grosbach03e2d442010-07-07 22:53:35 +00001845 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001846 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001847 // table that branches back to the actual target. This is a very simple
1848 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001849 MachineBasicBlock *TBB = 0, *FBB = 0;
1850 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001851 SmallVector<MachineOperand, 4> CondPrior;
1852 MachineFunction::iterator BBi = BB;
1853 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001854
Jim Grosbachca215e72009-11-16 17:10:56 +00001855 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001856 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001857
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001858 // If the block ends in an unconditional branch, move it. The prior block
1859 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001860 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001861 if (!B && Cond.empty() && BB != MF.begin() &&
1862 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001863 BB->moveAfter(JTBB);
1864 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001865 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001866 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001867 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001868 ++NumJTMoved;
1869 return NULL;
1870 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001871
1872 // Create a new MBB for the code after the jump BB.
1873 MachineBasicBlock *NewBB =
1874 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1875 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1876 MF.insert(MBBI, NewBB);
1877
1878 // Add an unconditional branch from NewBB to BB.
1879 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1880 // correspond directly to anything in the source.
1881 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001882 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001883
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001884 // Update internal data structures to account for the newly inserted MBB.
1885 MF.RenumberBlocks(NewBB);
1886
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001887 // Update the CFG.
1888 NewBB->addSuccessor(BB);
1889 JTBB->removeSuccessor(BB);
1890 JTBB->addSuccessor(NewBB);
1891
Jim Grosbach80697d12009-11-12 17:25:07 +00001892 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001893 return NewBB;
1894}