blob: 0a27d179e907ba8678432c101b4e50d0e274fe84 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000034#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000035using namespace llvm;
36
Evan Chenga1efbbd2009-08-14 00:32:16 +000037STATISTIC(NumCPEs, "Number of constpool entries");
38STATISTIC(NumSplit, "Number of uncond branches inserted");
39STATISTIC(NumCBrFixed, "Number of cond branches fixed");
40STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
41STATISTIC(NumTBs, "Number of table branches generated");
42STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000043STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chenga8e29892007-01-19 07:51:42 +000044
45namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000046 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000047 /// requires constant pool entries to be scattered among the instructions
48 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000049 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000050 /// special instructions.
51 ///
52 /// The terminology used in this pass includes:
53 /// Islands - Clumps of constants placed in the function.
54 /// Water - Potential places where an island could be formed.
55 /// CPE - A constant pool entry that has been placed somewhere, which
56 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000057 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000058 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000059 /// by MBB Number. The two-byte pads required for Thumb alignment are
60 /// counted as part of the following block (i.e., the offset and size for
61 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000062 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000063
Dale Johannesen99c49a42007-02-25 00:47:03 +000064 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000065 /// The two-byte pads required for Thumb alignment are counted as part of
66 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000067 std::vector<unsigned> BBOffsets;
68
Evan Chenga8e29892007-01-19 07:51:42 +000069 /// WaterList - A sorted list of basic blocks where islands could be placed
70 /// (i.e. blocks that don't fall through to the following block, due
71 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000072 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000073
Bob Wilsonb9239532009-10-15 20:49:47 +000074 /// NewWaterList - The subset of WaterList that was created since the
75 /// previous iteration by inserting unconditional branches.
76 SmallSet<MachineBasicBlock*, 4> NewWaterList;
77
Bob Wilson034de5f2009-10-12 18:52:13 +000078 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
79
Evan Chenga8e29892007-01-19 07:51:42 +000080 /// CPUser - One user of a constant pool, keeping the machine instruction
81 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000082 /// allowed from the instruction to the CP. The HighWaterMark records the
83 /// highest basic block where a new CPEntry can be placed. To ensure this
84 /// pass terminates, the CP entries are initially placed at the end of the
85 /// function and then move monotonically to lower addresses. The
86 /// exception to this rule is when the current CP entry for a particular
87 /// CPUser is out of range, but there is another CP entry for the same
88 /// constant value in range. We want to use the existing in-range CP
89 /// entry, but if it later moves out of range, the search for new water
90 /// should resume where it left off. The HighWaterMark is used to record
91 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +000092 struct CPUser {
93 MachineInstr *MI;
94 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +000095 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +000096 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000097 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000098 bool IsSoImm;
99 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
100 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000101 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
102 HighWaterMark = CPEMI->getParent();
103 }
Evan Chenga8e29892007-01-19 07:51:42 +0000104 };
Bob Wilson84945262009-05-12 17:09:30 +0000105
Evan Chenga8e29892007-01-19 07:51:42 +0000106 /// CPUsers - Keep track of all of the machine instructions that use various
107 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000108 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000109
Evan Chengc99ef082007-02-09 20:54:44 +0000110 /// CPEntry - One per constant pool entry, keeping the machine instruction
111 /// pointer, the constpool index, and the number of CPUser's which
112 /// reference this entry.
113 struct CPEntry {
114 MachineInstr *CPEMI;
115 unsigned CPI;
116 unsigned RefCount;
117 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
118 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
119 };
120
121 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000122 /// instructions. For each original constpool index (i.e. those that
123 /// existed upon entry to this pass), it keeps a vector of entries.
124 /// Original elements are cloned as we go along; the clones are
125 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000126 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000127
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000128 /// ImmBranch - One per immediate branch, keeping the machine instruction
129 /// pointer, conditional or unconditional, the max displacement,
130 /// and (if isCond is true) the corresponding unconditional branch
131 /// opcode.
132 struct ImmBranch {
133 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000134 unsigned MaxDisp : 31;
135 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000136 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000137 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
138 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000139 };
140
Evan Cheng2706f972007-05-16 05:14:06 +0000141 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000142 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000143 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000144
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000145 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
146 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000147 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000148
Evan Cheng5657c012009-07-29 02:18:14 +0000149 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
150 SmallVector<MachineInstr*, 4> T2JumpTables;
151
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000152 /// HasFarJump - True if any far jump instruction has been emitted during
153 /// the branch fix up pass.
154 bool HasFarJump;
155
Evan Chenga8e29892007-01-19 07:51:42 +0000156 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000157 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000158 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000159 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000160 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000161 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000162 public:
Devang Patel19974732007-05-03 01:11:54 +0000163 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000164 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000165
Evan Cheng5657c012009-07-29 02:18:14 +0000166 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000167
168 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000169 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000170 }
Bob Wilson84945262009-05-12 17:09:30 +0000171
Evan Chenga8e29892007-01-19 07:51:42 +0000172 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000173 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000174 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000175 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000176 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000177 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000178 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000179 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000180 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000181 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000182 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000183 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000184 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000185 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000186 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000187 void RemoveDeadCPEMI(MachineInstr *CPEMI);
188 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000189 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000190 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
191 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000192 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000193 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000194 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000195 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000196 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000197 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
198 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
199 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000200 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000201 bool OptimizeThumb2Instructions(MachineFunction &MF);
202 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000203 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000204
Evan Chenga8e29892007-01-19 07:51:42 +0000205 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000206 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000207 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000208 };
Devang Patel19974732007-05-03 01:11:54 +0000209 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000210}
211
Dale Johannesen8593e412007-04-29 19:19:30 +0000212/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000213void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000214 assert(BBOffsets.size() == BBSizes.size());
215 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
216 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000217 if (!isThumb)
218 return;
219#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000220 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000221 MBBI != E; ++MBBI) {
222 MachineBasicBlock *MBB = MBBI;
223 if (!MBB->empty() &&
224 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
225 unsigned MBBId = MBB->getNumber();
226 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
227 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000228 }
229 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000230#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000231}
232
233/// print block size and offset information - debugging
234void ARMConstantIslands::dumpBBs() {
235 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000236 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
237 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000238 }
239}
240
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000241/// createARMConstantIslandPass - returns an instance of the constpool
242/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000243FunctionPass *llvm::createARMConstantIslandPass() {
244 return new ARMConstantIslands();
245}
246
Evan Cheng5657c012009-07-29 02:18:14 +0000247bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
248 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000249
Evan Cheng5657c012009-07-29 02:18:14 +0000250 TII = MF.getTarget().getInstrInfo();
251 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000252 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
253
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000254 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000255 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000256 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000257
258 HasFarJump = false;
259
Evan Chenga8e29892007-01-19 07:51:42 +0000260 // Renumber all of the machine basic blocks in the function, guaranteeing that
261 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000262 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000263
Evan Chengd26b14c2009-07-31 18:28:05 +0000264 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000265 // This is so we can keep exact track of where the alignment padding goes.
266
Evan Chengd26b14c2009-07-31 18:28:05 +0000267 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000268 // aligned.
269 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000270
Evan Chenga8e29892007-01-19 07:51:42 +0000271 // Perform the initial placement of the constant pool entries. To start with,
272 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000273 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000274 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000275 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000276 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000277 AFI->setAlign(2U);
278 }
Bob Wilson84945262009-05-12 17:09:30 +0000279
Evan Chenga8e29892007-01-19 07:51:42 +0000280 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000281 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000282
Evan Chenga8e29892007-01-19 07:51:42 +0000283 // Do the initial scan of the function, building up information about the
284 // sizes of each block, the location of all the water, and finding all of the
285 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000286 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000287 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000288
Evan Chenged884f32007-04-03 23:39:48 +0000289 /// Remove dead constant pool entries.
290 RemoveUnusedCPEntries();
291
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000292 // Iteratively place constant pool entries and fix up branches until there
293 // is no change.
294 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000295 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000296 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000297 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000298 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000299 CPChange |= HandleConstantPoolUser(MF, i);
300 if (CPChange && ++NoCPIters > 30)
301 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000302 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000303
304 // Clear NewWaterList now. If we split a block for branches, it should
305 // appear as "new water" for the next iteration of constant pool placement.
306 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000307
308 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000309 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000310 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
311 if (BRChange && ++NoBRIters > 30)
312 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000313 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000314
315 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000316 break;
317 MadeChange = true;
318 }
Evan Chenged884f32007-04-03 23:39:48 +0000319
Evan Chenga1efbbd2009-08-14 00:32:16 +0000320 // Shrink 32-bit Thumb2 branch, load, and store instructions.
321 if (isThumb2)
322 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000323
Dale Johannesen8593e412007-04-29 19:19:30 +0000324 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000325 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000326
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000327 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
328 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000329 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000330 MadeChange |= UndoLRSpillRestore();
331
Evan Chenga8e29892007-01-19 07:51:42 +0000332 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000333 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000334 WaterList.clear();
335 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000336 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000337 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000338 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000339 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000340
341 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000342}
343
344/// DoInitialPlacement - Perform the initial placement of the constant pool
345/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000346void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000347 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000348 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000349 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
350 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000351
Evan Chenga8e29892007-01-19 07:51:42 +0000352 // Add all of the constants from the constant pool to the end block, use an
353 // identity mapping of CPI's to CPE's.
354 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000355 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000356
Evan Cheng5657c012009-07-29 02:18:14 +0000357 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000358 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000359 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000360 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
361 // we would have to pad them out or something so that instructions stay
362 // aligned.
363 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
364 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000365 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000366 .addImm(i).addConstantPoolIndex(i).addImm(Size);
367 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000368
369 // Add a new CPEntry, but no corresponding CPUser yet.
370 std::vector<CPEntry> CPEs;
371 CPEs.push_back(CPEntry(CPEMI, i));
372 CPEntries.push_back(CPEs);
373 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000374 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
375 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000376 }
377}
378
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000379/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000380/// into the block immediately after it.
381static bool BBHasFallthrough(MachineBasicBlock *MBB) {
382 // Get the next machine basic block in the function.
383 MachineFunction::iterator MBBI = MBB;
384 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
385 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000386
Evan Chenga8e29892007-01-19 07:51:42 +0000387 MachineBasicBlock *NextBB = next(MBBI);
388 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
389 E = MBB->succ_end(); I != E; ++I)
390 if (*I == NextBB)
391 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000392
Evan Chenga8e29892007-01-19 07:51:42 +0000393 return false;
394}
395
Evan Chengc99ef082007-02-09 20:54:44 +0000396/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
397/// look up the corresponding CPEntry.
398ARMConstantIslands::CPEntry
399*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
400 const MachineInstr *CPEMI) {
401 std::vector<CPEntry> &CPEs = CPEntries[CPI];
402 // Number of entries per constpool index should be small, just do a
403 // linear search.
404 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
405 if (CPEs[i].CPEMI == CPEMI)
406 return &CPEs[i];
407 }
408 return NULL;
409}
410
Evan Chenga8e29892007-01-19 07:51:42 +0000411/// InitialFunctionScan - Do the initial scan of the function, building up
412/// information about the sizes of each block, the location of all the water,
413/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000414void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000415 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000416 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000417 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000418 MBBI != E; ++MBBI) {
419 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000420
Evan Chenga8e29892007-01-19 07:51:42 +0000421 // If this block doesn't fall through into the next MBB, then this is
422 // 'water' that a constant pool island could be placed.
423 if (!BBHasFallthrough(&MBB))
424 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000425
Evan Chenga8e29892007-01-19 07:51:42 +0000426 unsigned MBBSize = 0;
427 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
428 I != E; ++I) {
429 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000430 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000431
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000432 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000433 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000434 bool isCond = false;
435 unsigned Bits = 0;
436 unsigned Scale = 1;
437 int UOpc = Opc;
438 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000439 default:
440 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000441 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000442 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000443 // be right, functions containing these must be 4-byte aligned.
444 AFI->setAlign(2U);
445 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000446 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000447 MBBSize += 2; // padding
448 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000449 case ARM::t2BR_JT:
450 T2JumpTables.push_back(I);
451 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000452 case ARM::Bcc:
453 isCond = true;
454 UOpc = ARM::B;
455 // Fallthrough
456 case ARM::B:
457 Bits = 24;
458 Scale = 4;
459 break;
460 case ARM::tBcc:
461 isCond = true;
462 UOpc = ARM::tB;
463 Bits = 8;
464 Scale = 2;
465 break;
466 case ARM::tB:
467 Bits = 11;
468 Scale = 2;
469 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000470 case ARM::t2Bcc:
471 isCond = true;
472 UOpc = ARM::t2B;
473 Bits = 20;
474 Scale = 2;
475 break;
476 case ARM::t2B:
477 Bits = 24;
478 Scale = 2;
479 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000480 }
Evan Chengb43216e2007-02-01 10:16:15 +0000481
482 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000483 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000484 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000485 }
486
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000487 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
488 PushPopMIs.push_back(I);
489
Evan Chengd3d9d662009-07-23 18:27:47 +0000490 if (Opc == ARM::CONSTPOOL_ENTRY)
491 continue;
492
Evan Chenga8e29892007-01-19 07:51:42 +0000493 // Scan the instructions for constant pool operands.
494 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000495 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000496 // We found one. The addressing mode tells us the max displacement
497 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000498
Evan Chenga8e29892007-01-19 07:51:42 +0000499 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000500 unsigned Bits = 0;
501 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000502 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000503 bool IsSoImm = false;
504
505 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000506 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000507 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000508 break;
509
510 // Taking the address of a CP entry.
511 case ARM::LEApcrel:
512 // This takes a SoImm, which is 8 bit immediate rotated. We'll
513 // pretend the maximum offset is 255 * 4. Since each instruction
514 // 4 byte wide, this is always correct. We'llc heck for other
515 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000516 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000517 Scale = 4;
518 NegOk = true;
519 IsSoImm = true;
520 break;
521 case ARM::t2LEApcrel:
522 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000523 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000524 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000525 case ARM::tLEApcrel:
526 Bits = 8;
527 Scale = 4;
528 break;
529
530 case ARM::LDR:
531 case ARM::LDRcp:
532 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000533 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000534 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000535 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000536
537 case ARM::tLDRpci:
538 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000539 Bits = 8;
540 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000541 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000542
543 case ARM::FLDD:
544 case ARM::FLDS:
545 Bits = 8;
546 Scale = 4; // +-(offset_8*4)
547 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000548 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000549 }
Evan Chengb43216e2007-02-01 10:16:15 +0000550
Evan Chenga8e29892007-01-19 07:51:42 +0000551 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000552 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000553 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000554 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000555 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000556
557 // Increment corresponding CPEntry reference count.
558 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
559 assert(CPE && "Cannot find a corresponding CPEntry!");
560 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000561
Evan Chenga8e29892007-01-19 07:51:42 +0000562 // Instructions can only use one CP entry, don't bother scanning the
563 // rest of the operands.
564 break;
565 }
566 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000567
Dale Johannesen8593e412007-04-29 19:19:30 +0000568 // In thumb mode, if this block is a constpool island, we may need padding
569 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000570 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000571 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000572 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
573 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000574 MBBSize += 2;
575
Evan Chenga8e29892007-01-19 07:51:42 +0000576 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000577 BBOffsets.push_back(Offset);
578 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000579 }
580}
581
Evan Chenga8e29892007-01-19 07:51:42 +0000582/// GetOffsetOf - Return the current offset of the specified machine instruction
583/// from the start of the function. This offset changes as stuff is moved
584/// around inside the function.
585unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
586 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000587
Evan Chenga8e29892007-01-19 07:51:42 +0000588 // The offset is composed of two things: the sum of the sizes of all MBB's
589 // before this instruction's block, and the offset from the start of the block
590 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000591 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000592
Dale Johannesen8593e412007-04-29 19:19:30 +0000593 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
594 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000595 if (isThumb &&
596 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000597 Offset%4 != 0)
598 Offset += 2;
599
Evan Chenga8e29892007-01-19 07:51:42 +0000600 // Sum instructions before MI in MBB.
601 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
602 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
603 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000604 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000605 }
606}
607
608/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
609/// ID.
610static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
611 const MachineBasicBlock *RHS) {
612 return LHS->getNumber() < RHS->getNumber();
613}
614
615/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
616/// machine function, it upsets all of the block numbers. Renumber the blocks
617/// and update the arrays that parallel this numbering.
618void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
619 // Renumber the MBB's to keep them consequtive.
620 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000621
Evan Chenga8e29892007-01-19 07:51:42 +0000622 // Insert a size into BBSizes to align it properly with the (newly
623 // renumbered) block numbers.
624 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000625
626 // Likewise for BBOffsets.
627 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000628
629 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000630 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000631 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000632 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
633 CompareMBBNumbers);
634 WaterList.insert(IP, NewBB);
635}
636
637
638/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000639/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000640/// account for this change and returns the newly created block.
641MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000642 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000643 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000644
645 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000646 MachineBasicBlock *NewBB =
647 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000648 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000649 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000650
Evan Chenga8e29892007-01-19 07:51:42 +0000651 // Splice the instructions starting with MI over to NewBB.
652 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000653
Evan Chenga8e29892007-01-19 07:51:42 +0000654 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000655 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000656 // There doesn't seem to be meaningful DebugInfo available; this doesn't
657 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000658 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
659 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000660 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000661
Evan Chenga8e29892007-01-19 07:51:42 +0000662 // Update the CFG. All succs of OrigBB are now succs of NewBB.
663 while (!OrigBB->succ_empty()) {
664 MachineBasicBlock *Succ = *OrigBB->succ_begin();
665 OrigBB->removeSuccessor(Succ);
666 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000667
Evan Chenga8e29892007-01-19 07:51:42 +0000668 // This pass should be run after register allocation, so there should be no
669 // PHI nodes to update.
670 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
671 && "PHI nodes should be eliminated by now!");
672 }
Bob Wilson84945262009-05-12 17:09:30 +0000673
Evan Chenga8e29892007-01-19 07:51:42 +0000674 // OrigBB branches to NewBB.
675 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000676
Evan Chenga8e29892007-01-19 07:51:42 +0000677 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000678 // This is almost the same as UpdateForInsertedWaterBlock, except that
679 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000680 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000681
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000682 // Insert a size into BBSizes to align it properly with the (newly
683 // renumbered) block numbers.
684 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000685
Dale Johannesen99c49a42007-02-25 00:47:03 +0000686 // Likewise for BBOffsets.
687 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
688
Bob Wilson84945262009-05-12 17:09:30 +0000689 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000690 // available water after it (but not if it's already there, which happens
691 // when splitting before a conditional branch that is followed by an
692 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000693 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000694 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
695 CompareMBBNumbers);
696 MachineBasicBlock* WaterBB = *IP;
697 if (WaterBB == OrigBB)
698 WaterList.insert(next(IP), NewBB);
699 else
700 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000701 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000702
Dale Johannesen8593e412007-04-29 19:19:30 +0000703 // Figure out how large the first NewMBB is. (It cannot
704 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000705 unsigned NewBBSize = 0;
706 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
707 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000708 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000709
Dale Johannesen99c49a42007-02-25 00:47:03 +0000710 unsigned OrigBBI = OrigBB->getNumber();
711 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000712 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000713 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000714
Evan Chenga8e29892007-01-19 07:51:42 +0000715 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000716 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000717 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000718 BBSizes[OrigBBI] -= NewBBSize - delta;
719
720 // ...and adjust BBOffsets for NewBB accordingly.
721 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
722
723 // All BBOffsets following these blocks must be modified.
724 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000725
726 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000727}
728
Dale Johannesen8593e412007-04-29 19:19:30 +0000729/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000730/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000731/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000732bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000733 unsigned TrialOffset, unsigned MaxDisp,
734 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000735 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
736 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000737 // Effectively, the valid range of displacements is 2 bytes smaller for such
738 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000739 unsigned TotalAdj = 0;
740 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000741 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000742 TotalAdj = 2;
743 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000744 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000745 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000746 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000747 TotalAdj += 2;
748 }
749
750 // In Thumb2 mode, later branch adjustments can shift instructions up and
751 // cause alignment change. In the worst case scenario this can cause the
752 // user's effective address to be subtracted by 2 and the CPE's address to
753 // be plus 2.
754 if (isThumb2 && TotalAdj != 4)
755 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000756
Dale Johannesen99c49a42007-02-25 00:47:03 +0000757 if (UserOffset <= TrialOffset) {
758 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000759 if (TrialOffset - UserOffset <= MaxDisp)
760 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000761 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000762 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000763 if (UserOffset - TrialOffset <= MaxDisp)
764 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000765 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000766 }
767 return false;
768}
769
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000770/// WaterIsInRange - Returns true if a CPE placed after the specified
771/// Water (a basic block) will be in range for the specific MI.
772
773bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000774 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000775 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000776 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000777 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000778
Dale Johannesend959aa42007-04-02 20:31:06 +0000779 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000780 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000781 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000782 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000783
Evan Chengd3d9d662009-07-23 18:27:47 +0000784 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000785}
786
787/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000788/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000789bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000790 MachineInstr *CPEMI, unsigned MaxDisp,
791 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000792 unsigned CPEOffset = GetOffsetOf(CPEMI);
793 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000794
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000795 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000796 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
797 << " max delta=" << MaxDisp
798 << " insn address=" << UserOffset
799 << " CPE address=" << CPEOffset
800 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000801 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000802
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000803 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000804}
805
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000806#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000807/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
808/// unconditionally branches to its only successor.
809static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
810 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
811 return false;
812
813 MachineBasicBlock *Succ = *MBB->succ_begin();
814 MachineBasicBlock *Pred = *MBB->pred_begin();
815 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000816 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
817 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000818 return PredMI->getOperand(0).getMBB() == Succ;
819 return false;
820}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000821#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000822
Bob Wilson84945262009-05-12 17:09:30 +0000823void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000824 int delta) {
825 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000826 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
827 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000828 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000829 // If some existing blocks have padding, adjust the padding as needed, a
830 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000831 if (!isThumb)
832 continue;
833 MachineBasicBlock *MBB = MBBI;
834 if (!MBB->empty()) {
835 // Constant pool entries require padding.
836 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000837 unsigned OldOffset = BBOffsets[i] - delta;
838 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000839 // add new padding
840 BBSizes[i] += 2;
841 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000842 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000843 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000844 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000845 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000846 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000847 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000848 // Thumb1 jump tables require padding. They should be at the end;
849 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000850 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000851 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000852 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
853 unsigned OldMIOffset = NewMIOffset - delta;
854 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000855 // remove existing padding
856 BBSizes[i] -= 2;
857 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000858 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000859 // add new padding
860 BBSizes[i] += 2;
861 delta += 2;
862 }
863 }
864 if (delta==0)
865 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000866 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000867 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000868 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000869}
870
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000871/// DecrementOldEntry - find the constant pool entry with index CPI
872/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000873/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000874/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000875
Evan Chenged884f32007-04-03 23:39:48 +0000876bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000877 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000878 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
879 assert(CPE && "Unexpected!");
880 if (--CPE->RefCount == 0) {
881 RemoveDeadCPEMI(CPEMI);
882 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000883 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884 return true;
885 }
886 return false;
887}
888
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000889/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
890/// if not, see if an in-range clone of the CPE is in range, and if so,
891/// change the data structures so the user references the clone. Returns:
892/// 0 = no existing entry found
893/// 1 = entry found, and there were no code insertions or deletions
894/// 2 = entry found, and there were code insertions or deletions
895int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
896{
897 MachineInstr *UserMI = U.MI;
898 MachineInstr *CPEMI = U.CPEMI;
899
900 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000901 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000902 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000904 }
905
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000907 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000908 std::vector<CPEntry> &CPEs = CPEntries[CPI];
909 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
910 // We already tried this one
911 if (CPEs[i].CPEMI == CPEMI)
912 continue;
913 // Removing CPEs can leave empty entries, skip
914 if (CPEs[i].CPEMI == NULL)
915 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000916 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000917 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
918 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000919 // Point the CPUser node to the replacement
920 U.CPEMI = CPEs[i].CPEMI;
921 // Change the CPI in the instruction operand to refer to the clone.
922 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000923 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000924 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000925 break;
926 }
927 // Adjust the refcount of the clone...
928 CPEs[i].RefCount++;
929 // ...and the original. If we didn't remove the old entry, none of the
930 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000931 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000932 }
933 }
934 return 0;
935}
936
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000937/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
938/// the specific unconditional branch instruction.
939static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000940 switch (Opc) {
941 case ARM::tB:
942 return ((1<<10)-1)*2;
943 case ARM::t2B:
944 return ((1<<23)-1)*2;
945 default:
946 break;
947 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000948
David Goodwin5e47a9a2009-06-30 18:04:13 +0000949 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000950}
951
Bob Wilsonb9239532009-10-15 20:49:47 +0000952/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000953/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +0000954/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +0000955/// is set to the WaterList entry. For Thumb, prefer water that will not
956/// introduce padding to water that will. To ensure that this pass
957/// terminates, the CPE location for a particular CPUser is only allowed to
958/// move to a lower address, so search backward from the end of the list and
959/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000960bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +0000961 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +0000962 if (WaterList.empty())
963 return false;
964
Bob Wilson32c50e82009-10-12 20:45:53 +0000965 bool FoundWaterThatWouldPad = false;
966 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000967 for (water_iterator IP = prior(WaterList.end()),
968 B = WaterList.begin();; --IP) {
969 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +0000970 // Check if water is in range and is either at a lower address than the
971 // current "high water mark" or a new water block that was created since
972 // the previous iteration by inserting an unconditional branch. In the
973 // latter case, we want to allow resetting the high water mark back to
974 // this new water since we haven't seen it before. Inserting branches
975 // should be relatively uncommon and when it does happen, we want to be
976 // sure to take advantage of it for all the CPEs near that block, so that
977 // we don't insert more branches than necessary.
978 if (WaterIsInRange(UserOffset, WaterBB, U) &&
979 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
980 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +0000981 unsigned WBBId = WaterBB->getNumber();
982 if (isThumb &&
983 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
984 // This is valid Water, but would introduce padding. Remember
985 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +0000986 if (!FoundWaterThatWouldPad) {
987 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +0000988 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000989 }
Bob Wilson3b757352009-10-12 19:04:03 +0000990 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +0000991 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +0000992 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +0000993 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000994 }
Bob Wilson3b757352009-10-12 19:04:03 +0000995 if (IP == B)
996 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000997 }
Bob Wilson32c50e82009-10-12 20:45:53 +0000998 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +0000999 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001000 return true;
1001 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001002 return false;
1003}
1004
Bob Wilson84945262009-05-12 17:09:30 +00001005/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001006/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1007/// block is used if in range, and the conditional branch munged so control
1008/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001009/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001010/// block following which the new island can be inserted (the WaterList
1011/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001012void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001013 unsigned UserOffset,
1014 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001015 CPUser &U = CPUsers[CPUserIndex];
1016 MachineInstr *UserMI = U.MI;
1017 MachineInstr *CPEMI = U.CPEMI;
1018 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001019 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001021 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001022
Bob Wilson36fa5322009-10-15 05:10:36 +00001023 // If the block does not end in an unconditional branch already, and if the
1024 // end of the block is within range, make new water there. (The addition
1025 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1026 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001027 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001028 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001029 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1030 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001031 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001032 if (&UserMBB->back() == UserMI)
1033 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001034 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001035 // Add an unconditional branch from UserMBB to fallthrough block.
1036 // Record it for branch lengthening; this new branch will not get out of
1037 // range, but if the preceding conditional branch is out of range, the
1038 // targets will be exchanged, and the altered branch may be out of
1039 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001040 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001041 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001042 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001043 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001044 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001045 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001046 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001047 BBSizes[UserMBB->getNumber()] += delta;
1048 AdjustBBOffsetsAfter(UserMBB, delta);
1049 } else {
1050 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001051 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001052 // and constant pool entries are 4 bytes: if instruction I references
1053 // island CPE, and instruction I+1 references CPE', it will
1054 // not work well to put CPE as far forward as possible, since then
1055 // CPE' cannot immediately follow it (that location is 2 bytes
1056 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001057 // a new island. So, we make a first guess, then walk through the
1058 // instructions between the one currently being looked at and the
1059 // possible insertion point, and make sure any other instructions
1060 // that reference CPEs will be able to use the same island area;
1061 // if not, we back up the insertion point.
1062
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001063 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001064 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001065 // island is handled inside OffsetIsInRange.
1066 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001067 // This could point off the end of the block if we've already got
1068 // constant pool entries following this block; only the last one is
1069 // in the water list. Back past any possible branches (allow for a
1070 // conditional and a maximally long unconditional).
1071 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001072 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001073 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001074 unsigned EndInsertOffset = BaseInsertOffset +
1075 CPEMI->getOperand(2).getImm();
1076 MachineBasicBlock::iterator MI = UserMI;
1077 ++MI;
1078 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001079 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001080 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001081 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001082 MI = next(MI)) {
1083 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001084 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001085 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001086 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1087 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1088 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001089 }
1090 // This is overly conservative, as we don't account for CPEMIs
1091 // being reused within the block, but it doesn't matter much.
1092 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1093 CPUIndex++;
1094 }
1095 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001096 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001097 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001098 }
1099}
1100
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001102/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001103/// place in-range. Return true if we changed any addresses (thus must run
1104/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001105bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001106 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001107 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001108 MachineInstr *UserMI = U.MI;
1109 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001110 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001111 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001112 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001113 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001114 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001115
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001116 // See if the current entry is within range, or there is a clone of it
1117 // in range.
1118 int result = LookForExistingCPEntry(U, UserOffset);
1119 if (result==1) return false;
1120 else if (result==2) return true;
1121
1122 // No existing clone of this CPE is within range.
1123 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001124 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001125
Bob Wilsonf98032e2009-10-12 21:23:15 +00001126 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001127 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1128 MachineBasicBlock *NewMBB;
1129 water_iterator IP;
1130 if (LookForWater(U, UserOffset, IP)) {
1131 DEBUG(errs() << "found water in range\n");
1132 MachineBasicBlock *WaterBB = *IP;
1133
1134 // If the original WaterList entry was "new water" on this iteration,
1135 // propagate that to the new island. This is just keeping NewWaterList
1136 // updated to match the WaterList, which will be updated below.
1137 if (NewWaterList.count(WaterBB)) {
1138 NewWaterList.erase(WaterBB);
1139 NewWaterList.insert(NewIsland);
1140 }
1141 // The new CPE goes before the following block (NewMBB).
1142 NewMBB = next(MachineFunction::iterator(WaterBB));
1143
1144 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001145 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001146 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001147 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001148
1149 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1150 // called while handling branches so that the water will be seen on the
1151 // next iteration for constant pools, but in this context, we don't want
1152 // it. Check for this so it will be removed from the WaterList.
1153 // Also remove any entry from NewWaterList.
1154 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1155 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1156 if (IP != WaterList.end())
1157 NewWaterList.erase(WaterBB);
1158
1159 // We are adding new water. Update NewWaterList.
1160 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001161 }
1162
Bob Wilsonb9239532009-10-15 20:49:47 +00001163 // Remove the original WaterList entry; we want subsequent insertions in
1164 // this vicinity to go after the one we're about to insert. This
1165 // considerably reduces the number of times we have to move the same CPE
1166 // more than once and is also important to ensure the algorithm terminates.
1167 if (IP != WaterList.end())
1168 WaterList.erase(IP);
1169
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001170 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001171 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001172
1173 // Update internal data structures to account for the newly inserted MBB.
1174 UpdateForInsertedWaterBlock(NewIsland);
1175
1176 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001177 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001178
1179 // Now that we have an island to add the CPE to, clone the original CPE and
1180 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001181 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001182 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1183 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001184 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001185 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001186 NumCPEs++;
1187
Dale Johannesen8593e412007-04-29 19:19:30 +00001188 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001189 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001190 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001191 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001192 // Increase the size of the island block to account for the new entry.
1193 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001194 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001195
Evan Chenga8e29892007-01-19 07:51:42 +00001196 // Finally, change the CPI in the instruction operand to be ID.
1197 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001198 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001199 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001200 break;
1201 }
Bob Wilson84945262009-05-12 17:09:30 +00001202
Chris Lattner705e07f2009-08-23 03:41:05 +00001203 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1204 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001205
Evan Chenga8e29892007-01-19 07:51:42 +00001206 return true;
1207}
1208
Evan Chenged884f32007-04-03 23:39:48 +00001209/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1210/// sizes and offsets of impacted basic blocks.
1211void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1212 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001213 unsigned Size = CPEMI->getOperand(2).getImm();
1214 CPEMI->eraseFromParent();
1215 BBSizes[CPEBB->getNumber()] -= Size;
1216 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001217 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001218 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001219 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001220 // empty, so fix this.
1221 // All succeeding offsets have the current size value added in, fix this.
1222 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001223 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001224 BBSizes[CPEBB->getNumber()] = 0;
1225 }
Evan Chenged884f32007-04-03 23:39:48 +00001226 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001227 AdjustBBOffsetsAfter(CPEBB, -Size);
1228 // An island has only one predecessor BB and one successor BB. Check if
1229 // this BB's predecessor jumps directly to this BB's successor. This
1230 // shouldn't happen currently.
1231 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1232 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001233}
1234
1235/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1236/// are zero.
1237bool ARMConstantIslands::RemoveUnusedCPEntries() {
1238 unsigned MadeChange = false;
1239 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1240 std::vector<CPEntry> &CPEs = CPEntries[i];
1241 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1242 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1243 RemoveDeadCPEMI(CPEs[j].CPEMI);
1244 CPEs[j].CPEMI = NULL;
1245 MadeChange = true;
1246 }
1247 }
Bob Wilson84945262009-05-12 17:09:30 +00001248 }
Evan Chenged884f32007-04-03 23:39:48 +00001249 return MadeChange;
1250}
1251
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001252/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001253/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001254bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1255 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001256 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001257 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001258 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001259
Chris Lattner705e07f2009-08-23 03:41:05 +00001260 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1261 << " from BB#" << MI->getParent()->getNumber()
1262 << " max delta=" << MaxDisp
1263 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1264 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001265
Dale Johannesen8593e412007-04-29 19:19:30 +00001266 if (BrOffset <= DestOffset) {
1267 // Branch before the Dest.
1268 if (DestOffset-BrOffset <= MaxDisp)
1269 return true;
1270 } else {
1271 if (BrOffset-DestOffset <= MaxDisp)
1272 return true;
1273 }
1274 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001275}
1276
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001277/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1278/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001279bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001280 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001281 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001282
Evan Chengc0dbec72007-01-31 19:57:44 +00001283 // Check to see if the DestBB is already in-range.
1284 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001285 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001286
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001287 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001288 return FixUpUnconditionalBr(MF, Br);
1289 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001290}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001291
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001292/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1293/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001294/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001295/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001296bool
Evan Cheng5657c012009-07-29 02:18:14 +00001297ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001298 MachineInstr *MI = Br.MI;
1299 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001300 if (!isThumb1)
1301 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001302
1303 // Use BL to implement far jump.
1304 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001305 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001306 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001307 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001308 HasFarJump = true;
1309 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001310
Chris Lattner705e07f2009-08-23 03:41:05 +00001311 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001312
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001313 return true;
1314}
1315
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001316/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001317/// far away to fit in its displacement field. It is converted to an inverse
1318/// conditional branch + an unconditional branch to the destination.
1319bool
Evan Cheng5657c012009-07-29 02:18:14 +00001320ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001321 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001322 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001323
Bob Wilson39bf0512009-05-12 17:35:29 +00001324 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001325 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001326 // blt L1
1327 // =>
1328 // bge L2
1329 // b L1
1330 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001331 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001332 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001333 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001334
1335 // If the branch is at the end of its MBB and that has a fall-through block,
1336 // direct the updated conditional branch to the fall-through block. Otherwise,
1337 // split the MBB before the next instruction.
1338 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001339 MachineInstr *BMI = &MBB->back();
1340 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001341
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001342 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001343 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001344 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001345 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001346 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001347 // condition and swap destinations:
1348 // beq L1
1349 // b L2
1350 // =>
1351 // bne L2
1352 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001353 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001354 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001355 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1356 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001357 BMI->getOperand(0).setMBB(DestBB);
1358 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001359 MI->getOperand(1).setImm(CC);
1360 return true;
1361 }
1362 }
1363 }
1364
1365 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001366 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001367 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001368 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001369 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001370 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001371 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1372 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001373 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001374 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001375 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001376 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001377
Chris Lattner893e1c92009-08-23 06:49:22 +00001378 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1379 << " also invert condition and change dest. to BB#"
1380 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001381
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001382 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001383 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001384 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1385 TII->get(MI->getOpcode()))
1386 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001387 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001388 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001389 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001390 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001391 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001392 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001393
1394 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001395 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001396 MI->eraseFromParent();
1397
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001398 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001399 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001400 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001401 return true;
1402}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001403
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001404/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001405/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1406/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001407bool ARMConstantIslands::UndoLRSpillRestore() {
1408 bool MadeChange = false;
1409 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1410 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001411 // First two operands are predicates, the third is a zero since there
1412 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001413 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001414 MI->getOperand(3).getReg() == ARM::PC &&
1415 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001416 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001417 MI->eraseFromParent();
1418 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001419 }
1420 }
1421 return MadeChange;
1422}
Evan Cheng5657c012009-07-29 02:18:14 +00001423
Evan Chenga1efbbd2009-08-14 00:32:16 +00001424bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1425 bool MadeChange = false;
1426
1427 // Shrink ADR and LDR from constantpool.
1428 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1429 CPUser &U = CPUsers[i];
1430 unsigned Opcode = U.MI->getOpcode();
1431 unsigned NewOpc = 0;
1432 unsigned Scale = 1;
1433 unsigned Bits = 0;
1434 switch (Opcode) {
1435 default: break;
1436 case ARM::t2LEApcrel:
1437 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1438 NewOpc = ARM::tLEApcrel;
1439 Bits = 8;
1440 Scale = 4;
1441 }
1442 break;
1443 case ARM::t2LDRpci:
1444 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1445 NewOpc = ARM::tLDRpci;
1446 Bits = 8;
1447 Scale = 4;
1448 }
1449 break;
1450 }
1451
1452 if (!NewOpc)
1453 continue;
1454
1455 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1456 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1457 // FIXME: Check if offset is multiple of scale if scale is not 4.
1458 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1459 U.MI->setDesc(TII->get(NewOpc));
1460 MachineBasicBlock *MBB = U.MI->getParent();
1461 BBSizes[MBB->getNumber()] -= 2;
1462 AdjustBBOffsetsAfter(MBB, -2);
1463 ++NumT2CPShrunk;
1464 MadeChange = true;
1465 }
1466 }
1467
Evan Chenga1efbbd2009-08-14 00:32:16 +00001468 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001469 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001470 return MadeChange;
1471}
1472
1473bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001474 bool MadeChange = false;
1475
1476 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1477 ImmBranch &Br = ImmBranches[i];
1478 unsigned Opcode = Br.MI->getOpcode();
1479 unsigned NewOpc = 0;
1480 unsigned Scale = 1;
1481 unsigned Bits = 0;
1482 switch (Opcode) {
1483 default: break;
1484 case ARM::t2B:
1485 NewOpc = ARM::tB;
1486 Bits = 11;
1487 Scale = 2;
1488 break;
1489 case ARM::t2Bcc:
1490 NewOpc = ARM::tBcc;
1491 Bits = 8;
1492 Scale = 2;
1493 break;
1494 }
1495 if (!NewOpc)
1496 continue;
1497
1498 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1499 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1500 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1501 Br.MI->setDesc(TII->get(NewOpc));
1502 MachineBasicBlock *MBB = Br.MI->getParent();
1503 BBSizes[MBB->getNumber()] -= 2;
1504 AdjustBBOffsetsAfter(MBB, -2);
1505 ++NumT2BrShrunk;
1506 MadeChange = true;
1507 }
1508 }
1509
1510 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001511}
1512
1513
1514/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1515/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001516bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1517 bool MadeChange = false;
1518
1519 // FIXME: After the tables are shrunk, can we get rid some of the
1520 // constantpool tables?
1521 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1522 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1523 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1524 MachineInstr *MI = T2JumpTables[i];
1525 const TargetInstrDesc &TID = MI->getDesc();
1526 unsigned NumOps = TID.getNumOperands();
1527 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1528 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1529 unsigned JTI = JTOP.getIndex();
1530 assert(JTI < JT.size());
1531
1532 bool ByteOk = true;
1533 bool HalfWordOk = true;
1534 unsigned JTOffset = GetOffsetOf(MI) + 4;
1535 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1536 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1537 MachineBasicBlock *MBB = JTBBs[j];
1538 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001539 // Negative offset is not ok. FIXME: We should change BB layout to make
1540 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001541 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001542 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001543 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001544 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001545 HalfWordOk = false;
1546 if (!ByteOk && !HalfWordOk)
1547 break;
1548 }
1549
1550 if (ByteOk || HalfWordOk) {
1551 MachineBasicBlock *MBB = MI->getParent();
1552 unsigned BaseReg = MI->getOperand(0).getReg();
1553 bool BaseRegKill = MI->getOperand(0).isKill();
1554 if (!BaseRegKill)
1555 continue;
1556 unsigned IdxReg = MI->getOperand(1).getReg();
1557 bool IdxRegKill = MI->getOperand(1).isKill();
1558 MachineBasicBlock::iterator PrevI = MI;
1559 if (PrevI == MBB->begin())
1560 continue;
1561
1562 MachineInstr *AddrMI = --PrevI;
1563 bool OptOk = true;
1564 // Examine the instruction that calculate the jumptable entry address.
1565 // If it's not the one just before the t2BR_JT, we won't delete it, then
1566 // it's not worth doing the optimization.
1567 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1568 const MachineOperand &MO = AddrMI->getOperand(k);
1569 if (!MO.isReg() || !MO.getReg())
1570 continue;
1571 if (MO.isDef() && MO.getReg() != BaseReg) {
1572 OptOk = false;
1573 break;
1574 }
1575 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1576 OptOk = false;
1577 break;
1578 }
1579 }
1580 if (!OptOk)
1581 continue;
1582
Evan Chenga1efbbd2009-08-14 00:32:16 +00001583 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1584 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001585 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001586 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1587 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001588 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001589 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001590
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001591 if (!OptOk)
1592 continue;
1593
1594 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1595 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1596 .addReg(IdxReg, getKillRegState(IdxRegKill))
1597 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1598 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1599 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1600 // is 2-byte aligned. For now, asm printer will fix it up.
1601 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1602 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1603 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1604 OrigSize += TII->GetInstSizeInBytes(MI);
1605
1606 AddrMI->eraseFromParent();
1607 LeaMI->eraseFromParent();
1608 MI->eraseFromParent();
1609
1610 int delta = OrigSize - NewSize;
1611 BBSizes[MBB->getNumber()] -= delta;
1612 AdjustBBOffsetsAfter(MBB, -delta);
1613
1614 ++NumTBs;
1615 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001616 }
1617 }
1618
1619 return MadeChange;
1620}