blob: b9d7b31ed2582664d8cc857d7d53ff1cbee96adb [file] [log] [blame]
Bill Wendling9a4d2e42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Chenga8e29892007-01-19 07:51:42 +00002//
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 Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000020#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.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"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
54namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000055 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000058 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// special instructions.
60 ///
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000066 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000067 /// BasicBlockInfo - Information about the offset and size of a single
68 /// basic block.
69 struct BasicBlockInfo {
70 /// Offset - Distance from the beginning of the function to the beginning
71 /// of this basic block.
72 ///
73 /// The two-byte pads required for Thumb alignment are counted as part of
74 /// the following block.
75 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +000076
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000077 /// Size - Size of the basic block in bytes. If the block contains
78 /// inline assembly, this is a worst case estimate.
79 ///
80 /// The two-byte pads required for Thumb alignment are counted as part of
81 /// the following block (i.e., the offset and size for a padded block
82 /// will both be ==2 mod 4).
83 unsigned Size;
84
85 BasicBlockInfo() : Offset(0), Size(0) {}
86 BasicBlockInfo(unsigned o, unsigned s) : Offset(o), Size(s) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +000087
88 /// Compute the offset immediately following this block.
89 unsigned postOffset() const { return Offset + Size; }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000090 };
91
92 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +000093
Evan Chenga8e29892007-01-19 07:51:42 +000094 /// WaterList - A sorted list of basic blocks where islands could be placed
95 /// (i.e. blocks that don't fall through to the following block, due
96 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000097 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000098
Bob Wilsonb9239532009-10-15 20:49:47 +000099 /// NewWaterList - The subset of WaterList that was created since the
100 /// previous iteration by inserting unconditional branches.
101 SmallSet<MachineBasicBlock*, 4> NewWaterList;
102
Bob Wilson034de5f2009-10-12 18:52:13 +0000103 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
104
Evan Chenga8e29892007-01-19 07:51:42 +0000105 /// CPUser - One user of a constant pool, keeping the machine instruction
106 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000107 /// allowed from the instruction to the CP. The HighWaterMark records the
108 /// highest basic block where a new CPEntry can be placed. To ensure this
109 /// pass terminates, the CP entries are initially placed at the end of the
110 /// function and then move monotonically to lower addresses. The
111 /// exception to this rule is when the current CP entry for a particular
112 /// CPUser is out of range, but there is another CP entry for the same
113 /// constant value in range. We want to use the existing in-range CP
114 /// entry, but if it later moves out of range, the search for new water
115 /// should resume where it left off. The HighWaterMark is used to record
116 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000117 struct CPUser {
118 MachineInstr *MI;
119 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000120 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000121 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000122 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000123 bool IsSoImm;
124 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
125 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000126 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
127 HighWaterMark = CPEMI->getParent();
128 }
Evan Chenga8e29892007-01-19 07:51:42 +0000129 };
Bob Wilson84945262009-05-12 17:09:30 +0000130
Evan Chenga8e29892007-01-19 07:51:42 +0000131 /// CPUsers - Keep track of all of the machine instructions that use various
132 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000133 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000134
Evan Chengc99ef082007-02-09 20:54:44 +0000135 /// CPEntry - One per constant pool entry, keeping the machine instruction
136 /// pointer, the constpool index, and the number of CPUser's which
137 /// reference this entry.
138 struct CPEntry {
139 MachineInstr *CPEMI;
140 unsigned CPI;
141 unsigned RefCount;
142 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
143 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
144 };
145
146 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000147 /// instructions. For each original constpool index (i.e. those that
148 /// existed upon entry to this pass), it keeps a vector of entries.
149 /// Original elements are cloned as we go along; the clones are
150 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000151 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000152
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000153 /// ImmBranch - One per immediate branch, keeping the machine instruction
154 /// pointer, conditional or unconditional, the max displacement,
155 /// and (if isCond is true) the corresponding unconditional branch
156 /// opcode.
157 struct ImmBranch {
158 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000159 unsigned MaxDisp : 31;
160 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000161 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000162 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
163 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000164 };
165
Evan Cheng2706f972007-05-16 05:14:06 +0000166 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000167 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000168 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000169
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000170 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
171 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000172 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000173
Evan Cheng5657c012009-07-29 02:18:14 +0000174 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
175 SmallVector<MachineInstr*, 4> T2JumpTables;
176
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000177 /// HasFarJump - True if any far jump instruction has been emitted during
178 /// the branch fix up pass.
179 bool HasFarJump;
180
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000181 /// HasInlineAsm - True if the function contains inline assembly.
182 bool HasInlineAsm;
183
Chris Lattner20628752010-07-22 21:27:00 +0000184 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000185 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000186 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000187 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000188 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000189 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000190 public:
Devang Patel19974732007-05-03 01:11:54 +0000191 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000192 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000193
Evan Cheng5657c012009-07-29 02:18:14 +0000194 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000195
196 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000197 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000198 }
Bob Wilson84945262009-05-12 17:09:30 +0000199
Evan Chenga8e29892007-01-19 07:51:42 +0000200 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000201 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000202 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000203 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000204 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000205 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000206 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000207 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000208 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000209 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000210 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000211 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000212 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000213 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000214 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000215 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000216 void RemoveDeadCPEMI(MachineInstr *CPEMI);
217 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000218 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000219 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
220 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000221 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000222 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000223 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000224 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000225 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000226 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
227 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
228 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000229 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000230 bool OptimizeThumb2Instructions(MachineFunction &MF);
231 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000232 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000233 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000234 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
235 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000236
Evan Chenga8e29892007-01-19 07:51:42 +0000237 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000238 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000239 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000240 };
Devang Patel19974732007-05-03 01:11:54 +0000241 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000242}
243
Dale Johannesen8593e412007-04-29 19:19:30 +0000244/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000245void ARMConstantIslands::verify(MachineFunction &MF) {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000246 for (unsigned i = 1, e = BBInfo.size(); i != e; ++i)
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000247 assert(BBInfo[i-1].postOffset() == BBInfo[i].Offset);
Evan Chengd3d9d662009-07-23 18:27:47 +0000248 if (!isThumb)
249 return;
250#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000251 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000252 MBBI != E; ++MBBI) {
253 MachineBasicBlock *MBB = MBBI;
254 if (!MBB->empty() &&
255 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
256 unsigned MBBId = MBB->getNumber();
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000257 assert(HasInlineAsm ||
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000258 (BBInfo[MBBId].Offset%4 == 0 && BBInfo[MBBId].Size%4 == 0) ||
259 (BBInfo[MBBId].Offset%4 != 0 && BBInfo[MBBId].Size%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000260 }
261 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000262 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
263 CPUser &U = CPUsers[i];
264 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000265 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
266 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
267 UserOffset - CPEOffset;
268 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000269 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000270#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000271}
272
273/// print block size and offset information - debugging
274void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000275 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
276 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
277 << " size " << BBInfo[J].Size << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000278 }
279}
280
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000281/// createARMConstantIslandPass - returns an instance of the constpool
282/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000283FunctionPass *llvm::createARMConstantIslandPass() {
284 return new ARMConstantIslands();
285}
286
Evan Cheng5657c012009-07-29 02:18:14 +0000287bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
288 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000289
Chris Lattner20628752010-07-22 21:27:00 +0000290 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000291 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000292 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
293
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000294 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000295 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000296 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000297
298 HasFarJump = false;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000299 HasInlineAsm = false;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000300
Evan Chenga8e29892007-01-19 07:51:42 +0000301 // Renumber all of the machine basic blocks in the function, guaranteeing that
302 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000303 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000304
Jim Grosbach80697d12009-11-12 17:25:07 +0000305 // Try to reorder and otherwise adjust the block layout to make good use
306 // of the TB[BH] instructions.
307 bool MadeChange = false;
308 if (isThumb2 && AdjustJumpTableBlocks) {
309 JumpTableFunctionScan(MF);
310 MadeChange |= ReorderThumb2JumpTables(MF);
311 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000312 T2JumpTables.clear();
313 // Blocks may have shifted around. Keep the numbering up to date.
314 MF.RenumberBlocks();
315 }
316
Evan Chengd26b14c2009-07-31 18:28:05 +0000317 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000318 // This is so we can keep exact track of where the alignment padding goes.
319
Chris Lattner7d7dab02010-01-27 23:37:36 +0000320 // ARM and Thumb2 functions need to be 4-byte aligned.
321 if (!isThumb1)
322 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000323
Evan Chenga8e29892007-01-19 07:51:42 +0000324 // Perform the initial placement of the constant pool entries. To start with,
325 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000326 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000327 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000328 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000329 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000330 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000331 }
Bob Wilson84945262009-05-12 17:09:30 +0000332
Evan Chenga8e29892007-01-19 07:51:42 +0000333 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000334 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000335
Evan Chenga8e29892007-01-19 07:51:42 +0000336 // Do the initial scan of the function, building up information about the
337 // sizes of each block, the location of all the water, and finding all of the
338 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000339 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000340 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000341 DEBUG(dumpBBs());
342
Bob Wilson84945262009-05-12 17:09:30 +0000343
Evan Chenged884f32007-04-03 23:39:48 +0000344 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000345 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000346
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000347 // Iteratively place constant pool entries and fix up branches until there
348 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000349 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000350 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000351 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000352 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000353 CPChange |= HandleConstantPoolUser(MF, i);
354 if (CPChange && ++NoCPIters > 30)
355 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000356 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000357
Bob Wilsonb9239532009-10-15 20:49:47 +0000358 // Clear NewWaterList now. If we split a block for branches, it should
359 // appear as "new water" for the next iteration of constant pool placement.
360 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000361
362 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000363 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000364 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
365 if (BRChange && ++NoBRIters > 30)
366 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000367 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000368
369 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000370 break;
371 MadeChange = true;
372 }
Evan Chenged884f32007-04-03 23:39:48 +0000373
Evan Chenga1efbbd2009-08-14 00:32:16 +0000374 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000375 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000376 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000377
Dale Johannesen8593e412007-04-29 19:19:30 +0000378 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000379 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000380
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000381 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
382 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000383 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000384 MadeChange |= UndoLRSpillRestore();
385
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000386 // Save the mapping between original and cloned constpool entries.
387 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
388 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
389 const CPEntry & CPE = CPEntries[i][j];
390 AFI->recordCPEClone(i, CPE.CPI);
391 }
392 }
393
Evan Chengb1c857b2010-07-22 02:09:47 +0000394 DEBUG(errs() << '\n'; dumpBBs());
395
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000396 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000397 WaterList.clear();
398 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000399 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000400 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000401 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000402 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000403
404 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000405}
406
407/// DoInitialPlacement - Perform the initial placement of the constant pool
408/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000409void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000410 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000411 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000412 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
413 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000414
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000415 // Mark the basic block as 4-byte aligned as required by the const-pool.
416 BB->setAlignment(2);
417
Evan Chenga8e29892007-01-19 07:51:42 +0000418 // Add all of the constants from the constant pool to the end block, use an
419 // identity mapping of CPI's to CPE's.
420 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000421 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000422
Evan Cheng5657c012009-07-29 02:18:14 +0000423 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000424 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000425 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000426 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
427 // we would have to pad them out or something so that instructions stay
428 // aligned.
429 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
430 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000431 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
432 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000433 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000434
435 // Add a new CPEntry, but no corresponding CPUser yet.
436 std::vector<CPEntry> CPEs;
437 CPEs.push_back(CPEntry(CPEMI, i));
438 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000439 ++NumCPEs;
Chris Lattner893e1c92009-08-23 06:49:22 +0000440 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
441 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000442 }
443}
444
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000445/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000446/// into the block immediately after it.
447static bool BBHasFallthrough(MachineBasicBlock *MBB) {
448 // Get the next machine basic block in the function.
449 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000450 // Can't fall off end of function.
451 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000452 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000453
Chris Lattner7896c9f2009-12-03 00:50:42 +0000454 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000455 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
456 E = MBB->succ_end(); I != E; ++I)
457 if (*I == NextBB)
458 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000459
Evan Chenga8e29892007-01-19 07:51:42 +0000460 return false;
461}
462
Evan Chengc99ef082007-02-09 20:54:44 +0000463/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
464/// look up the corresponding CPEntry.
465ARMConstantIslands::CPEntry
466*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
467 const MachineInstr *CPEMI) {
468 std::vector<CPEntry> &CPEs = CPEntries[CPI];
469 // Number of entries per constpool index should be small, just do a
470 // linear search.
471 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
472 if (CPEs[i].CPEMI == CPEMI)
473 return &CPEs[i];
474 }
475 return NULL;
476}
477
Jim Grosbach80697d12009-11-12 17:25:07 +0000478/// JumpTableFunctionScan - Do a scan of the function, building up
479/// information about the sizes of each block and the locations of all
480/// the jump tables.
481void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000482 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
483 MBBI != E; ++MBBI) {
484 MachineBasicBlock &MBB = *MBBI;
485
Jim Grosbach80697d12009-11-12 17:25:07 +0000486 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000487 I != E; ++I)
488 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
489 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000490 }
491}
492
Evan Chenga8e29892007-01-19 07:51:42 +0000493/// InitialFunctionScan - Do the initial scan of the function, building up
494/// information about the sizes of each block, the location of all the water,
495/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000496void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000497 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000498 // First thing, see if the function has any inline assembly in it. If so,
499 // we have to be conservative about alignment assumptions, as we don't
500 // know for sure the size of any instructions in the inline assembly.
501 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
502 MBBI != E; ++MBBI) {
503 MachineBasicBlock &MBB = *MBBI;
504 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
505 I != E; ++I)
506 if (I->getOpcode() == ARM::INLINEASM)
507 HasInlineAsm = true;
508 }
509
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000510 // Now go back through the instructions and build up our data structures.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000511 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000512 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000513 MBBI != E; ++MBBI) {
514 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000515
Evan Chenga8e29892007-01-19 07:51:42 +0000516 // If this block doesn't fall through into the next MBB, then this is
517 // 'water' that a constant pool island could be placed.
518 if (!BBHasFallthrough(&MBB))
519 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000520
Evan Chenga8e29892007-01-19 07:51:42 +0000521 unsigned MBBSize = 0;
522 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
523 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000524 if (I->isDebugValue())
525 continue;
Evan Chenga8e29892007-01-19 07:51:42 +0000526 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000527 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000528
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000529 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000530 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000531 bool isCond = false;
532 unsigned Bits = 0;
533 unsigned Scale = 1;
534 int UOpc = Opc;
535 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000536 default:
537 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000538 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000539 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000540 // be right, functions containing these must be 4-byte aligned.
Evan Chengb1c857b2010-07-22 02:09:47 +0000541 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
Jakob Stoklund Olesen6fbea432011-12-06 22:41:31 +0000542 // table entries. So this code checks whether offset of tBR_JTr + 2
543 // is aligned. That is held in Offset+MBBSize, which already has
544 // 2 added in for the size of the mov pc instruction.
Chris Lattner7d7dab02010-01-27 23:37:36 +0000545 MF.EnsureAlignment(2U);
Jakob Stoklund Olesen6fbea432011-12-06 22:41:31 +0000546 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
547 // FIXME: Add a pseudo ALIGN instruction instead.
548 MBBSize += 2; // padding
Dale Johannesen8593e412007-04-29 19:19:30 +0000549 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000550 case ARM::t2BR_JT:
551 T2JumpTables.push_back(I);
552 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000553 case ARM::Bcc:
554 isCond = true;
555 UOpc = ARM::B;
556 // Fallthrough
557 case ARM::B:
558 Bits = 24;
559 Scale = 4;
560 break;
561 case ARM::tBcc:
562 isCond = true;
563 UOpc = ARM::tB;
564 Bits = 8;
565 Scale = 2;
566 break;
567 case ARM::tB:
568 Bits = 11;
569 Scale = 2;
570 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000571 case ARM::t2Bcc:
572 isCond = true;
573 UOpc = ARM::t2B;
574 Bits = 20;
575 Scale = 2;
576 break;
577 case ARM::t2B:
578 Bits = 24;
579 Scale = 2;
580 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000581 }
Evan Chengb43216e2007-02-01 10:16:15 +0000582
583 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000584 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000585 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000586 }
587
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000588 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
589 PushPopMIs.push_back(I);
590
Evan Chengd3d9d662009-07-23 18:27:47 +0000591 if (Opc == ARM::CONSTPOOL_ENTRY)
592 continue;
593
Evan Chenga8e29892007-01-19 07:51:42 +0000594 // Scan the instructions for constant pool operands.
595 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000596 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000597 // We found one. The addressing mode tells us the max displacement
598 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000599
Evan Chenga8e29892007-01-19 07:51:42 +0000600 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000601 unsigned Bits = 0;
602 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000603 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000604 bool IsSoImm = false;
605
606 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000607 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000608 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000609 break;
610
611 // Taking the address of a CP entry.
612 case ARM::LEApcrel:
613 // This takes a SoImm, which is 8 bit immediate rotated. We'll
614 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000615 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000616 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000617 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000618 Scale = 4;
619 NegOk = true;
620 IsSoImm = true;
621 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000622 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000623 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000624 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000625 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000626 case ARM::tLEApcrel:
627 Bits = 8;
628 Scale = 4;
629 break;
630
Jim Grosbach3e556122010-10-26 22:37:02 +0000631 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000632 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000633 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000634 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000635 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000636 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000637
638 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000639 Bits = 8;
640 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000641 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000642
Jim Grosbache5165492009-11-09 00:11:35 +0000643 case ARM::VLDRD:
644 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000645 Bits = 8;
646 Scale = 4; // +-(offset_8*4)
647 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000648 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000649 }
Evan Chengb43216e2007-02-01 10:16:15 +0000650
Evan Chenga8e29892007-01-19 07:51:42 +0000651 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000652 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000653 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000654 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000655 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000656
657 // Increment corresponding CPEntry reference count.
658 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
659 assert(CPE && "Cannot find a corresponding CPEntry!");
660 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000661
Evan Chenga8e29892007-01-19 07:51:42 +0000662 // Instructions can only use one CP entry, don't bother scanning the
663 // rest of the operands.
664 break;
665 }
666 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000667
Dale Johannesen8593e412007-04-29 19:19:30 +0000668 // In thumb mode, if this block is a constpool island, we may need padding
669 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000670 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000671 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000672 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000673 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000674 MBBSize += 2;
675
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000676 BBInfo.push_back(BasicBlockInfo(Offset, MBBSize));
Dale Johannesen99c49a42007-02-25 00:47:03 +0000677 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000678 }
679}
680
Evan Chenga8e29892007-01-19 07:51:42 +0000681/// GetOffsetOf - Return the current offset of the specified machine instruction
682/// from the start of the function. This offset changes as stuff is moved
683/// around inside the function.
684unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
685 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000686
Evan Chenga8e29892007-01-19 07:51:42 +0000687 // The offset is composed of two things: the sum of the sizes of all MBB's
688 // before this instruction's block, and the offset from the start of the block
689 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000690 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000691
Dale Johannesen8593e412007-04-29 19:19:30 +0000692 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
693 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000694 if (isThumb &&
695 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000696 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000697 Offset += 2;
698
Evan Chenga8e29892007-01-19 07:51:42 +0000699 // Sum instructions before MI in MBB.
700 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
701 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
702 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000703 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000704 }
705}
706
707/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
708/// ID.
709static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
710 const MachineBasicBlock *RHS) {
711 return LHS->getNumber() < RHS->getNumber();
712}
713
714/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
715/// machine function, it upsets all of the block numbers. Renumber the blocks
716/// and update the arrays that parallel this numbering.
717void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000718 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000719 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000720
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000721 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000722 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000723 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000724
725 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000726 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000727 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000728 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
729 CompareMBBNumbers);
730 WaterList.insert(IP, NewBB);
731}
732
733
734/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000735/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000736/// account for this change and returns the newly created block.
737MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000738 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000739 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000740
741 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000742 MachineBasicBlock *NewBB =
743 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000744 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000745 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000746
Evan Chenga8e29892007-01-19 07:51:42 +0000747 // Splice the instructions starting with MI over to NewBB.
748 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000749
Evan Chenga8e29892007-01-19 07:51:42 +0000750 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000751 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000752 // There doesn't seem to be meaningful DebugInfo available; this doesn't
753 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000754 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000755 if (!isThumb)
756 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
757 else
758 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
759 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000760 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000761
Evan Chenga8e29892007-01-19 07:51:42 +0000762 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000763 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000764
Evan Chenga8e29892007-01-19 07:51:42 +0000765 // OrigBB branches to NewBB.
766 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000767
Evan Chenga8e29892007-01-19 07:51:42 +0000768 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000769 // This is almost the same as UpdateForInsertedWaterBlock, except that
770 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000771 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000772
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000773 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000774 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000775 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000776
Bob Wilson84945262009-05-12 17:09:30 +0000777 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000778 // available water after it (but not if it's already there, which happens
779 // when splitting before a conditional branch that is followed by an
780 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000781 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000782 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
783 CompareMBBNumbers);
784 MachineBasicBlock* WaterBB = *IP;
785 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000786 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000787 else
788 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000789 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000790
Dale Johannesen99c49a42007-02-25 00:47:03 +0000791 unsigned OrigBBI = OrigBB->getNumber();
792 unsigned NewBBI = NewBB->getNumber();
Bob Wilson84945262009-05-12 17:09:30 +0000793
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000794 int delta = isThumb1 ? 2 : 4;
Dale Johannesen8086d582010-07-23 22:50:23 +0000795
796 // Figure out how large the OrigBB is. As the first half of the original
797 // block, it cannot contain a tablejump. The size includes
798 // the new jump we added. (It should be possible to do this without
799 // recounting everything, but it's very confusing, and this is rarely
800 // executed.)
801 unsigned OrigBBSize = 0;
802 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
803 I != E; ++I)
804 OrigBBSize += TII->GetInstSizeInBytes(I);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000805 BBInfo[OrigBBI].Size = OrigBBSize;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000806
807 // ...and adjust BBOffsets for NewBB accordingly.
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000808 BBInfo[NewBBI].Offset = BBInfo[OrigBBI].postOffset();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000809
Dale Johannesen8086d582010-07-23 22:50:23 +0000810 // Figure out how large the NewMBB is. As the second half of the original
811 // block, it may contain a tablejump.
812 unsigned NewBBSize = 0;
813 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
814 I != E; ++I)
815 NewBBSize += TII->GetInstSizeInBytes(I);
816 // Set the size of NewBB in BBSizes. It does not include any padding now.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000817 BBInfo[NewBBI].Size = NewBBSize;
Dale Johannesen8086d582010-07-23 22:50:23 +0000818
Jakob Stoklund Olesen6fbea432011-12-06 22:41:31 +0000819 MachineInstr* ThumbJTMI = prior(NewBB->end());
820 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
821 // We've added another 2-byte instruction before this tablejump, which
822 // means we will always need padding if we didn't before, and vice versa.
823
824 // The original offset of the jump instruction was:
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000825 unsigned OrigOffset = BBInfo[OrigBBI].postOffset() - delta;
Jakob Stoklund Olesen6fbea432011-12-06 22:41:31 +0000826 if (OrigOffset%4 == 0) {
827 // We had padding before and now we don't. No net change in code size.
828 delta = 0;
829 } else {
830 // We didn't have padding before and now we do.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000831 BBInfo[NewBBI].Size += 2;
Jakob Stoklund Olesen6fbea432011-12-06 22:41:31 +0000832 delta = 4;
833 }
834 }
835
Dale Johannesen99c49a42007-02-25 00:47:03 +0000836 // All BBOffsets following these blocks must be modified.
Dale Johannesen8086d582010-07-23 22:50:23 +0000837 if (delta)
838 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000839
840 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000841}
842
Dale Johannesen8593e412007-04-29 19:19:30 +0000843/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000844/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000845/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000846bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000847 unsigned TrialOffset, unsigned MaxDisp,
848 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000849 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
850 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000851 // Effectively, the valid range of displacements is 2 bytes smaller for such
852 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000853 unsigned TotalAdj = 0;
854 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000855 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000856 TotalAdj = 2;
857 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000858 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000859 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000860 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000861 TotalAdj += 2;
862 }
863
864 // In Thumb2 mode, later branch adjustments can shift instructions up and
865 // cause alignment change. In the worst case scenario this can cause the
866 // user's effective address to be subtracted by 2 and the CPE's address to
867 // be plus 2.
868 if (isThumb2 && TotalAdj != 4)
869 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000870
Dale Johannesen99c49a42007-02-25 00:47:03 +0000871 if (UserOffset <= TrialOffset) {
872 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000873 if (TrialOffset - UserOffset <= MaxDisp)
874 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000875 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000876 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000877 if (UserOffset - TrialOffset <= MaxDisp)
878 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000879 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000880 }
881 return false;
882}
883
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884/// WaterIsInRange - Returns true if a CPE placed after the specified
885/// Water (a basic block) will be in range for the specific MI.
886
887bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000888 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000889 unsigned MaxDisp = U.MaxDisp;
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000890 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000891
Dale Johannesend959aa42007-04-02 20:31:06 +0000892 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000893 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000894 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000895 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000896
Evan Chengd3d9d662009-07-23 18:27:47 +0000897 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898}
899
900/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000901/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000902bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000903 MachineInstr *CPEMI, unsigned MaxDisp,
904 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000905 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000906 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000907
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000908 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000909 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
910 << " max delta=" << MaxDisp
911 << " insn address=" << UserOffset
912 << " CPE address=" << CPEOffset
913 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000914 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000915
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000916 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000917}
918
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000919#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000920/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
921/// unconditionally branches to its only successor.
922static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
923 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
924 return false;
925
926 MachineBasicBlock *Succ = *MBB->succ_begin();
927 MachineBasicBlock *Pred = *MBB->pred_begin();
928 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000929 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
930 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000931 return PredMI->getOperand(0).getMBB() == Succ;
932 return false;
933}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000934#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000935
Bob Wilson84945262009-05-12 17:09:30 +0000936void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000937 int delta) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000938 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000939 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
940 i < e; ++i) {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000941 BBInfo[i].Offset += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000942 // If some existing blocks have padding, adjust the padding as needed, a
943 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000944 if (!isThumb)
945 continue;
946 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000947 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000948 // Constant pool entries require padding.
949 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000950 unsigned OldOffset = BBInfo[i].Offset - delta;
951 if ((OldOffset%4) == 0 && (BBInfo[i].Offset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000952 // add new padding
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000953 BBInfo[i].Size += 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000954 delta += 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000955 } else if ((OldOffset%4) != 0 && (BBInfo[i].Offset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000956 // remove existing padding
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000957 BBInfo[i].Size -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000958 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000959 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000960 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000961 // Thumb1 jump tables require padding. They should be at the end;
962 // following unconditional branches are removed by AnalyzeBranch.
Evan Chengb1c857b2010-07-22 02:09:47 +0000963 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
Dale Johannesen8086d582010-07-23 22:50:23 +0000964 // table entries. So this code checks whether offset of tBR_JTr
965 // is aligned; if it is, the offset of the jump table following the
966 // instruction will not be aligned, and we need padding.
Evan Cheng78947622009-07-24 18:20:44 +0000967 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000968 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Dale Johannesen8086d582010-07-23 22:50:23 +0000969 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
Evan Cheng4a8ea212009-08-11 07:36:14 +0000970 unsigned OldMIOffset = NewMIOffset - delta;
971 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000972 // remove existing padding
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000973 BBInfo[i].Size -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000974 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000975 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000976 // add new padding
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000977 BBInfo[i].Size += 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000978 delta += 2;
979 }
980 }
981 if (delta==0)
982 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000983 }
Chris Lattner7896c9f2009-12-03 00:50:42 +0000984 MBBI = llvm::next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000985 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000986}
987
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000988/// DecrementOldEntry - find the constant pool entry with index CPI
989/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000990/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000991/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000992
Evan Chenged884f32007-04-03 23:39:48 +0000993bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000994 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000995 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
996 assert(CPE && "Unexpected!");
997 if (--CPE->RefCount == 0) {
998 RemoveDeadCPEMI(CPEMI);
999 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001000 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001001 return true;
1002 }
1003 return false;
1004}
1005
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001006/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1007/// if not, see if an in-range clone of the CPE is in range, and if so,
1008/// change the data structures so the user references the clone. Returns:
1009/// 0 = no existing entry found
1010/// 1 = entry found, and there were no code insertions or deletions
1011/// 2 = entry found, and there were code insertions or deletions
1012int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1013{
1014 MachineInstr *UserMI = U.MI;
1015 MachineInstr *CPEMI = U.CPEMI;
1016
1017 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001018 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001019 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001020 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001021 }
1022
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001023 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001024 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001025 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1026 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1027 // We already tried this one
1028 if (CPEs[i].CPEMI == CPEMI)
1029 continue;
1030 // Removing CPEs can leave empty entries, skip
1031 if (CPEs[i].CPEMI == NULL)
1032 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001033 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001034 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1035 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001036 // Point the CPUser node to the replacement
1037 U.CPEMI = CPEs[i].CPEMI;
1038 // Change the CPI in the instruction operand to refer to the clone.
1039 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001040 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001041 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001042 break;
1043 }
1044 // Adjust the refcount of the clone...
1045 CPEs[i].RefCount++;
1046 // ...and the original. If we didn't remove the old entry, none of the
1047 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001048 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001049 }
1050 }
1051 return 0;
1052}
1053
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001054/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1055/// the specific unconditional branch instruction.
1056static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001057 switch (Opc) {
1058 case ARM::tB:
1059 return ((1<<10)-1)*2;
1060 case ARM::t2B:
1061 return ((1<<23)-1)*2;
1062 default:
1063 break;
1064 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001065
David Goodwin5e47a9a2009-06-30 18:04:13 +00001066 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001067}
1068
Bob Wilsonb9239532009-10-15 20:49:47 +00001069/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001070/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001071/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001072/// is set to the WaterList entry. For Thumb, prefer water that will not
1073/// introduce padding to water that will. To ensure that this pass
1074/// terminates, the CPE location for a particular CPUser is only allowed to
1075/// move to a lower address, so search backward from the end of the list and
1076/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001077bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001078 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001079 if (WaterList.empty())
1080 return false;
1081
Bob Wilson32c50e82009-10-12 20:45:53 +00001082 bool FoundWaterThatWouldPad = false;
1083 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001084 for (water_iterator IP = prior(WaterList.end()),
1085 B = WaterList.begin();; --IP) {
1086 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001087 // Check if water is in range and is either at a lower address than the
1088 // current "high water mark" or a new water block that was created since
1089 // the previous iteration by inserting an unconditional branch. In the
1090 // latter case, we want to allow resetting the high water mark back to
1091 // this new water since we haven't seen it before. Inserting branches
1092 // should be relatively uncommon and when it does happen, we want to be
1093 // sure to take advantage of it for all the CPEs near that block, so that
1094 // we don't insert more branches than necessary.
1095 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1096 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1097 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001098 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001099 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001100 // This is valid Water, but would introduce padding. Remember
1101 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001102 if (!FoundWaterThatWouldPad) {
1103 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001104 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001105 }
Bob Wilson3b757352009-10-12 19:04:03 +00001106 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001107 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001108 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001109 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001110 }
Bob Wilson3b757352009-10-12 19:04:03 +00001111 if (IP == B)
1112 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001113 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001114 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001115 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001116 return true;
1117 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001118 return false;
1119}
1120
Bob Wilson84945262009-05-12 17:09:30 +00001121/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001122/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1123/// block is used if in range, and the conditional branch munged so control
1124/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001125/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001126/// block following which the new island can be inserted (the WaterList
1127/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001128void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001129 unsigned UserOffset,
1130 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001131 CPUser &U = CPUsers[CPUserIndex];
1132 MachineInstr *UserMI = U.MI;
1133 MachineInstr *CPEMI = U.CPEMI;
1134 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001135 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
1136 assert(OffsetOfNextBlock == BBInfo[UserMBB->getNumber()+1].Offset);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001137
Bob Wilson36fa5322009-10-15 05:10:36 +00001138 // If the block does not end in an unconditional branch already, and if the
1139 // end of the block is within range, make new water there. (The addition
1140 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1141 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001142 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001143 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001144 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1145 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001146 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001147 if (&UserMBB->back() == UserMI)
1148 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001149 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001150 // Add an unconditional branch from UserMBB to fallthrough block.
1151 // Record it for branch lengthening; this new branch will not get out of
1152 // range, but if the preceding conditional branch is out of range, the
1153 // targets will be exchanged, and the altered branch may be out of
1154 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001155 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001156 if (!isThumb)
1157 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1158 else
1159 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1160 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001161 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001162 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001163 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001164 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001165 BBInfo[UserMBB->getNumber()].Size += delta;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001166 AdjustBBOffsetsAfter(UserMBB, delta);
1167 } else {
1168 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001169 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001170 // and constant pool entries are 4 bytes: if instruction I references
1171 // island CPE, and instruction I+1 references CPE', it will
1172 // not work well to put CPE as far forward as possible, since then
1173 // CPE' cannot immediately follow it (that location is 2 bytes
1174 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001175 // a new island. So, we make a first guess, then walk through the
1176 // instructions between the one currently being looked at and the
1177 // possible insertion point, and make sure any other instructions
1178 // that reference CPEs will be able to use the same island area;
1179 // if not, we back up the insertion point.
1180
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001181 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001182 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001183 // island is handled inside OffsetIsInRange.
1184 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001185 // This could point off the end of the block if we've already got
1186 // constant pool entries following this block; only the last one is
1187 // in the water list. Back past any possible branches (allow for a
1188 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001189 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1190 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001191 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001192 unsigned EndInsertOffset = BaseInsertOffset +
1193 CPEMI->getOperand(2).getImm();
1194 MachineBasicBlock::iterator MI = UserMI;
1195 ++MI;
1196 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001197 unsigned NumCPUsers = CPUsers.size();
1198 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001199 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001200 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001201 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001202 MI = llvm::next(MI)) {
1203 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001204 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001205 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001206 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1207 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1208 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001209 }
1210 // This is overly conservative, as we don't account for CPEMIs
1211 // being reused within the block, but it doesn't matter much.
1212 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1213 CPUIndex++;
1214 }
Evan Cheng719510a2010-08-12 20:30:05 +00001215
1216 // Remember the last IT instruction.
1217 if (MI->getOpcode() == ARM::t2IT)
1218 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001219 }
Evan Cheng719510a2010-08-12 20:30:05 +00001220
Chris Lattner893e1c92009-08-23 06:49:22 +00001221 DEBUG(errs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001222 --MI;
1223
1224 // Avoid splitting an IT block.
1225 if (LastIT) {
1226 unsigned PredReg = 0;
1227 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1228 if (CC != ARMCC::AL)
1229 MI = LastIT;
1230 }
1231 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001232 }
1233}
1234
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001235/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001236/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001237/// place in-range. Return true if we changed any addresses (thus must run
1238/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001239bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001240 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001241 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001242 MachineInstr *UserMI = U.MI;
1243 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001244 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001245 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001246 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001247 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001248 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001249
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001250 // See if the current entry is within range, or there is a clone of it
1251 // in range.
1252 int result = LookForExistingCPEntry(U, UserOffset);
1253 if (result==1) return false;
1254 else if (result==2) return true;
1255
1256 // No existing clone of this CPE is within range.
1257 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001258 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001259
Bob Wilsonf98032e2009-10-12 21:23:15 +00001260 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001261 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1262 MachineBasicBlock *NewMBB;
1263 water_iterator IP;
1264 if (LookForWater(U, UserOffset, IP)) {
1265 DEBUG(errs() << "found water in range\n");
1266 MachineBasicBlock *WaterBB = *IP;
1267
1268 // If the original WaterList entry was "new water" on this iteration,
1269 // propagate that to the new island. This is just keeping NewWaterList
1270 // updated to match the WaterList, which will be updated below.
1271 if (NewWaterList.count(WaterBB)) {
1272 NewWaterList.erase(WaterBB);
1273 NewWaterList.insert(NewIsland);
1274 }
1275 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001276 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001277
1278 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001279 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001280 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001281 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001282
1283 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1284 // called while handling branches so that the water will be seen on the
1285 // next iteration for constant pools, but in this context, we don't want
1286 // it. Check for this so it will be removed from the WaterList.
1287 // Also remove any entry from NewWaterList.
1288 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1289 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1290 if (IP != WaterList.end())
1291 NewWaterList.erase(WaterBB);
1292
1293 // We are adding new water. Update NewWaterList.
1294 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001295 }
1296
Bob Wilsonb9239532009-10-15 20:49:47 +00001297 // Remove the original WaterList entry; we want subsequent insertions in
1298 // this vicinity to go after the one we're about to insert. This
1299 // considerably reduces the number of times we have to move the same CPE
1300 // more than once and is also important to ensure the algorithm terminates.
1301 if (IP != WaterList.end())
1302 WaterList.erase(IP);
1303
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001304 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001305 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001306
1307 // Update internal data structures to account for the newly inserted MBB.
1308 UpdateForInsertedWaterBlock(NewIsland);
1309
1310 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001311 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001312
1313 // Now that we have an island to add the CPE to, clone the original CPE and
1314 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001315 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001316 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001317 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001318 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001319 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001320
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001321 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1322 NewIsland->setAlignment(2);
1323
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001324 BBInfo[NewIsland->getNumber()].Offset = BBInfo[NewMBB->getNumber()].Offset;
Evan Chengb43216e2007-02-01 10:16:15 +00001325 // Compensate for .align 2 in thumb mode.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001326 if (isThumb && (BBInfo[NewIsland->getNumber()].Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001327 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001328 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001329 BBInfo[NewIsland->getNumber()].Size += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001330 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001331
Evan Chenga8e29892007-01-19 07:51:42 +00001332 // Finally, change the CPI in the instruction operand to be ID.
1333 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001334 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001335 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001336 break;
1337 }
Bob Wilson84945262009-05-12 17:09:30 +00001338
Chris Lattner705e07f2009-08-23 03:41:05 +00001339 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1340 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001341
Evan Chenga8e29892007-01-19 07:51:42 +00001342 return true;
1343}
1344
Evan Chenged884f32007-04-03 23:39:48 +00001345/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1346/// sizes and offsets of impacted basic blocks.
1347void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1348 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001349 unsigned Size = CPEMI->getOperand(2).getImm();
1350 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001351 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001352 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001353 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001354 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001355 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001356 // empty, so fix this.
1357 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001358 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1359 Size += BBInfo[CPEBB->getNumber()].Size;
1360 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001361 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001362
1363 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1364 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001365 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001366 AdjustBBOffsetsAfter(CPEBB, -Size);
1367 // An island has only one predecessor BB and one successor BB. Check if
1368 // this BB's predecessor jumps directly to this BB's successor. This
1369 // shouldn't happen currently.
1370 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1371 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001372}
1373
1374/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1375/// are zero.
1376bool ARMConstantIslands::RemoveUnusedCPEntries() {
1377 unsigned MadeChange = false;
1378 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1379 std::vector<CPEntry> &CPEs = CPEntries[i];
1380 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1381 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1382 RemoveDeadCPEMI(CPEs[j].CPEMI);
1383 CPEs[j].CPEMI = NULL;
1384 MadeChange = true;
1385 }
1386 }
Bob Wilson84945262009-05-12 17:09:30 +00001387 }
Evan Chenged884f32007-04-03 23:39:48 +00001388 return MadeChange;
1389}
1390
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001391/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001392/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001393bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1394 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001395 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001396 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001397 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001398
Chris Lattner705e07f2009-08-23 03:41:05 +00001399 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1400 << " from BB#" << MI->getParent()->getNumber()
1401 << " max delta=" << MaxDisp
1402 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1403 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001404
Dale Johannesen8593e412007-04-29 19:19:30 +00001405 if (BrOffset <= DestOffset) {
1406 // Branch before the Dest.
1407 if (DestOffset-BrOffset <= MaxDisp)
1408 return true;
1409 } else {
1410 if (BrOffset-DestOffset <= MaxDisp)
1411 return true;
1412 }
1413 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001414}
1415
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001416/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1417/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001418bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001419 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001420 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001421
Evan Chengc0dbec72007-01-31 19:57:44 +00001422 // Check to see if the DestBB is already in-range.
1423 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001424 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001425
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001426 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001427 return FixUpUnconditionalBr(MF, Br);
1428 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001429}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001430
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001431/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1432/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001433/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001434/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001435bool
Evan Cheng5657c012009-07-29 02:18:14 +00001436ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001437 MachineInstr *MI = Br.MI;
1438 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001439 if (!isThumb1)
1440 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001441
1442 // Use BL to implement far jump.
1443 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001444 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001445 BBInfo[MBB->getNumber()].Size += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001446 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001447 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001448 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001449
Chris Lattner705e07f2009-08-23 03:41:05 +00001450 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001451
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001452 return true;
1453}
1454
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001455/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001456/// far away to fit in its displacement field. It is converted to an inverse
1457/// conditional branch + an unconditional branch to the destination.
1458bool
Evan Cheng5657c012009-07-29 02:18:14 +00001459ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001460 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001461 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001462
Bob Wilson39bf0512009-05-12 17:35:29 +00001463 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001464 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001465 // blt L1
1466 // =>
1467 // bge L2
1468 // b L1
1469 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001470 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001471 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001472 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001473
1474 // If the branch is at the end of its MBB and that has a fall-through block,
1475 // direct the updated conditional branch to the fall-through block. Otherwise,
1476 // split the MBB before the next instruction.
1477 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001478 MachineInstr *BMI = &MBB->back();
1479 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001480
Dan Gohmanfe601042010-06-22 15:08:57 +00001481 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001482 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001483 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001484 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001485 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001486 // condition and swap destinations:
1487 // beq L1
1488 // b L2
1489 // =>
1490 // bne L2
1491 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001492 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001493 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001494 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1495 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001496 BMI->getOperand(0).setMBB(DestBB);
1497 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001498 MI->getOperand(1).setImm(CC);
1499 return true;
1500 }
1501 }
1502 }
1503
1504 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001505 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001506 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001507 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001508 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001509 BBInfo[MBB->getNumber()].Size -= delta;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001510 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
Dale Johannesen8593e412007-04-29 19:19:30 +00001511 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001512 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001513 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001514 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001515 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001516
Chris Lattner893e1c92009-08-23 06:49:22 +00001517 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1518 << " also invert condition and change dest. to BB#"
1519 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001520
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001521 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001522 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001523 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001524 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001525 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001526 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001527 if (isThumb)
1528 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1529 .addImm(ARMCC::AL).addReg(0);
1530 else
1531 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001532 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001533 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001534 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001535
1536 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001537 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001538 MI->eraseFromParent();
1539
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001540 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001541 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001542 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001543 return true;
1544}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001545
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001546/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001547/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1548/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001549bool ARMConstantIslands::UndoLRSpillRestore() {
1550 bool MadeChange = false;
1551 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1552 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001553 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001554 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001555 MI->getOperand(2).getReg() == ARM::PC &&
1556 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001557 // Create the new insn and copy the predicate from the old.
1558 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1559 .addOperand(MI->getOperand(0))
1560 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001561 MI->eraseFromParent();
1562 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001563 }
1564 }
1565 return MadeChange;
1566}
Evan Cheng5657c012009-07-29 02:18:14 +00001567
Evan Chenga1efbbd2009-08-14 00:32:16 +00001568bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1569 bool MadeChange = false;
1570
1571 // Shrink ADR and LDR from constantpool.
1572 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1573 CPUser &U = CPUsers[i];
1574 unsigned Opcode = U.MI->getOpcode();
1575 unsigned NewOpc = 0;
1576 unsigned Scale = 1;
1577 unsigned Bits = 0;
1578 switch (Opcode) {
1579 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001580 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001581 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1582 NewOpc = ARM::tLEApcrel;
1583 Bits = 8;
1584 Scale = 4;
1585 }
1586 break;
1587 case ARM::t2LDRpci:
1588 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1589 NewOpc = ARM::tLDRpci;
1590 Bits = 8;
1591 Scale = 4;
1592 }
1593 break;
1594 }
1595
1596 if (!NewOpc)
1597 continue;
1598
1599 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1600 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1601 // FIXME: Check if offset is multiple of scale if scale is not 4.
1602 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1603 U.MI->setDesc(TII->get(NewOpc));
1604 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001605 BBInfo[MBB->getNumber()].Size -= 2;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001606 AdjustBBOffsetsAfter(MBB, -2);
1607 ++NumT2CPShrunk;
1608 MadeChange = true;
1609 }
1610 }
1611
Evan Chenga1efbbd2009-08-14 00:32:16 +00001612 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001613 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001614 return MadeChange;
1615}
1616
1617bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001618 bool MadeChange = false;
1619
1620 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1621 ImmBranch &Br = ImmBranches[i];
1622 unsigned Opcode = Br.MI->getOpcode();
1623 unsigned NewOpc = 0;
1624 unsigned Scale = 1;
1625 unsigned Bits = 0;
1626 switch (Opcode) {
1627 default: break;
1628 case ARM::t2B:
1629 NewOpc = ARM::tB;
1630 Bits = 11;
1631 Scale = 2;
1632 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001633 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001634 NewOpc = ARM::tBcc;
1635 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001636 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001637 break;
1638 }
Evan Chengde17fb62009-10-31 23:46:45 +00001639 }
1640 if (NewOpc) {
1641 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1642 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1643 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1644 Br.MI->setDesc(TII->get(NewOpc));
1645 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001646 BBInfo[MBB->getNumber()].Size -= 2;
Evan Chengde17fb62009-10-31 23:46:45 +00001647 AdjustBBOffsetsAfter(MBB, -2);
1648 ++NumT2BrShrunk;
1649 MadeChange = true;
1650 }
1651 }
1652
1653 Opcode = Br.MI->getOpcode();
1654 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001655 continue;
1656
Evan Chengde17fb62009-10-31 23:46:45 +00001657 NewOpc = 0;
1658 unsigned PredReg = 0;
1659 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1660 if (Pred == ARMCC::EQ)
1661 NewOpc = ARM::tCBZ;
1662 else if (Pred == ARMCC::NE)
1663 NewOpc = ARM::tCBNZ;
1664 if (!NewOpc)
1665 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001666 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001667 // Check if the distance is within 126. Subtract starting offset by 2
1668 // because the cmp will be eliminated.
1669 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001670 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001671 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001672 MachineBasicBlock::iterator CmpMI = Br.MI;
1673 if (CmpMI != Br.MI->getParent()->begin()) {
1674 --CmpMI;
1675 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1676 unsigned Reg = CmpMI->getOperand(0).getReg();
1677 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1678 if (Pred == ARMCC::AL &&
1679 CmpMI->getOperand(1).getImm() == 0 &&
1680 isARMLowRegister(Reg)) {
1681 MachineBasicBlock *MBB = Br.MI->getParent();
1682 MachineInstr *NewBR =
1683 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1684 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1685 CmpMI->eraseFromParent();
1686 Br.MI->eraseFromParent();
1687 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001688 BBInfo[MBB->getNumber()].Size -= 2;
Evan Cheng0539c152011-04-01 22:09:28 +00001689 AdjustBBOffsetsAfter(MBB, -2);
1690 ++NumCBZ;
1691 MadeChange = true;
1692 }
Evan Chengde17fb62009-10-31 23:46:45 +00001693 }
1694 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001695 }
1696 }
1697
1698 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001699}
1700
Evan Chenga1efbbd2009-08-14 00:32:16 +00001701/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1702/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001703bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1704 bool MadeChange = false;
1705
1706 // FIXME: After the tables are shrunk, can we get rid some of the
1707 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001708 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001709 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001710
Evan Cheng5657c012009-07-29 02:18:14 +00001711 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1712 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1713 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001714 const MCInstrDesc &MCID = MI->getDesc();
1715 unsigned NumOps = MCID.getNumOperands();
1716 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001717 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1718 unsigned JTI = JTOP.getIndex();
1719 assert(JTI < JT.size());
1720
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001721 bool ByteOk = true;
1722 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001723 unsigned JTOffset = GetOffsetOf(MI) + 4;
1724 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001725 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1726 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001727 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001728 // Negative offset is not ok. FIXME: We should change BB layout to make
1729 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001730 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001731 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001732 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001733 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001734 HalfWordOk = false;
1735 if (!ByteOk && !HalfWordOk)
1736 break;
1737 }
1738
1739 if (ByteOk || HalfWordOk) {
1740 MachineBasicBlock *MBB = MI->getParent();
1741 unsigned BaseReg = MI->getOperand(0).getReg();
1742 bool BaseRegKill = MI->getOperand(0).isKill();
1743 if (!BaseRegKill)
1744 continue;
1745 unsigned IdxReg = MI->getOperand(1).getReg();
1746 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001747
1748 // Scan backwards to find the instruction that defines the base
1749 // register. Due to post-RA scheduling, we can't count on it
1750 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001751 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001752 MachineBasicBlock::iterator B = MBB->begin();
1753 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1754 --PrevI;
1755
1756 // If for some reason we didn't find it, we can't do anything, so
1757 // just skip this one.
1758 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001759 continue;
1760
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001761 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001762 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001763 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001764 // Make sure it only defines the base register and kills any uses
1765 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001766 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1767 const MachineOperand &MO = AddrMI->getOperand(k);
1768 if (!MO.isReg() || !MO.getReg())
1769 continue;
1770 if (MO.isDef() && MO.getReg() != BaseReg) {
1771 OptOk = false;
1772 break;
1773 }
1774 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1775 OptOk = false;
1776 break;
1777 }
1778 }
1779 if (!OptOk)
1780 continue;
1781
Owen Anderson6b8719f2010-12-13 22:51:08 +00001782 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001783 // that gave us the initial base register definition.
1784 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1785 ;
1786
Owen Anderson6b8719f2010-12-13 22:51:08 +00001787 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001788 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001789 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001790 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001791 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001792 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001793 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001794
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001795 if (!OptOk)
1796 continue;
1797
Jim Grosbachd092a872010-11-29 21:28:32 +00001798 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001799 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1800 .addReg(IdxReg, getKillRegState(IdxRegKill))
1801 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1802 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1803 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1804 // is 2-byte aligned. For now, asm printer will fix it up.
1805 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1806 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1807 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1808 OrigSize += TII->GetInstSizeInBytes(MI);
1809
1810 AddrMI->eraseFromParent();
1811 LeaMI->eraseFromParent();
1812 MI->eraseFromParent();
1813
1814 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001815 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001816 AdjustBBOffsetsAfter(MBB, -delta);
1817
1818 ++NumTBs;
1819 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001820 }
1821 }
1822
1823 return MadeChange;
1824}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001825
Jim Grosbach9249efe2009-11-16 18:55:47 +00001826/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1827/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001828bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1829 bool MadeChange = false;
1830
1831 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001832 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001833
Jim Grosbach80697d12009-11-12 17:25:07 +00001834 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1835 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1836 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001837 const MCInstrDesc &MCID = MI->getDesc();
1838 unsigned NumOps = MCID.getNumOperands();
1839 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001840 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1841 unsigned JTI = JTOP.getIndex();
1842 assert(JTI < JT.size());
1843
1844 // We prefer if target blocks for the jump table come after the jump
1845 // instruction so we can use TB[BH]. Loop through the target blocks
1846 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001847 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001848 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1849 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1850 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001851 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001852
Jim Grosbach08cbda52009-11-16 18:58:52 +00001853 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001854 // The destination precedes the switch. Try to move the block forward
1855 // so we have a positive offset.
1856 MachineBasicBlock *NewBB =
1857 AdjustJTTargetBlockForward(MBB, MI->getParent());
1858 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001859 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001860 MadeChange = true;
1861 }
1862 }
1863 }
1864
1865 return MadeChange;
1866}
1867
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001868MachineBasicBlock *ARMConstantIslands::
1869AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1870{
1871 MachineFunction &MF = *BB->getParent();
1872
Jim Grosbach03e2d442010-07-07 22:53:35 +00001873 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001874 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001875 // table that branches back to the actual target. This is a very simple
1876 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001877 MachineBasicBlock *TBB = 0, *FBB = 0;
1878 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001879 SmallVector<MachineOperand, 4> CondPrior;
1880 MachineFunction::iterator BBi = BB;
1881 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001882
Jim Grosbachca215e72009-11-16 17:10:56 +00001883 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001884 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001885
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001886 // If the block ends in an unconditional branch, move it. The prior block
1887 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001888 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001889 if (!B && Cond.empty() && BB != MF.begin() &&
1890 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001891 BB->moveAfter(JTBB);
1892 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001893 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001894 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001895 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001896 ++NumJTMoved;
1897 return NULL;
1898 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001899
1900 // Create a new MBB for the code after the jump BB.
1901 MachineBasicBlock *NewBB =
1902 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1903 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1904 MF.insert(MBBI, NewBB);
1905
1906 // Add an unconditional branch from NewBB to BB.
1907 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1908 // correspond directly to anything in the source.
1909 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001910 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1911 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001912
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001913 // Update internal data structures to account for the newly inserted MBB.
1914 MF.RenumberBlocks(NewBB);
1915
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001916 // Update the CFG.
1917 NewBB->addSuccessor(BB);
1918 JTBB->removeSuccessor(BB);
1919 JTBB->addSuccessor(NewBB);
1920
Jim Grosbach80697d12009-11-12 17:25:07 +00001921 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001922 return NewBB;
1923}