blob: 7babb58679754830609d1113fec619f9faaef6dc [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"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000029#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000055static cl::opt<bool>
56AlignConstantIslands("arm-align-constant-island", cl::Hidden,
57 cl::desc("Align constant islands in code"));
58
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000059/// UnknownPadding - Return the worst case padding that could result from
60/// unknown offset bits. This does not include alignment padding caused by
61/// known offset bits.
62///
63/// @param LogAlign log2(alignment)
64/// @param KnownBits Number of known low offset bits.
65static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
66 if (KnownBits < LogAlign)
67 return (1u << LogAlign) - (1u << KnownBits);
68 return 0;
69}
70
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000071/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
72/// add padding such that:
73///
74/// 1. The result is aligned to 1 << LogAlign.
75///
76/// 2. No other value of the unknown bits would require more padding.
77///
78/// This may add more padding than is required to satisfy just one of the
79/// constraints. It is necessary to compute alignment this way to guarantee
80/// that we don't underestimate the padding before an aligned block. If the
81/// real padding before a block is larger than we think, constant pool entries
82/// may go out of range.
83static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
84 unsigned KnownBits) {
85 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000086 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000087
88 // Then align the result.
89 return RoundUpToAlignment(Offset, 1u << LogAlign);
90}
91
Evan Chenga8e29892007-01-19 07:51:42 +000092namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000093 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000094 /// requires constant pool entries to be scattered among the instructions
95 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000096 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000097 /// special instructions.
98 ///
99 /// The terminology used in this pass includes:
100 /// Islands - Clumps of constants placed in the function.
101 /// Water - Potential places where an island could be formed.
102 /// CPE - A constant pool entry that has been placed somewhere, which
103 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000104 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000105 /// BasicBlockInfo - Information about the offset and size of a single
106 /// basic block.
107 struct BasicBlockInfo {
108 /// Offset - Distance from the beginning of the function to the beginning
109 /// of this basic block.
110 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000111 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000112 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000113
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000114 /// Size - Size of the basic block in bytes. If the block contains
115 /// inline assembly, this is a worst case estimate.
116 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000117 /// The size does not include any alignment padding whether from the
118 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000119 unsigned Size;
120
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000121 /// KnownBits - The number of low bits in Offset that are known to be
122 /// exact. The remaining bits of Offset are an upper bound.
123 uint8_t KnownBits;
124
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000125 /// Unalign - When non-zero, the block contains instructions (inline asm)
126 /// of unknown size. The real size may be smaller than Size bytes by a
127 /// multiple of 1 << Unalign.
128 uint8_t Unalign;
129
130 /// PostAlign - When non-zero, the block terminator contains a .align
131 /// directive, so the end of the block is aligned to 1 << PostAlign
132 /// bytes.
133 uint8_t PostAlign;
134
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000135 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
136 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000137
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000138 /// Compute the number of known offset bits internally to this block.
139 /// This number should be used to predict worst case padding when
140 /// splitting the block.
141 unsigned internalKnownBits() const {
142 return Unalign ? Unalign : KnownBits;
143 }
144
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000145 /// Compute the offset immediately following this block. If LogAlign is
146 /// specified, return the offset the successor block will get if it has
147 /// this alignment.
148 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000149 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000150 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
151 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000152 return PO;
153 // Add alignment padding from the terminator.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000154 return WorstCaseAlign(PO, LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000155 }
156
157 /// Compute the number of known low bits of postOffset. If this block
158 /// contains inline asm, the number of known bits drops to the
159 /// instruction alignment. An aligned terminator may increase the number
160 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000161 /// If LogAlign is given, also consider the alignment of the next block.
162 unsigned postKnownBits(unsigned LogAlign = 0) const {
163 return std::max(std::max(unsigned(PostAlign), LogAlign),
164 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000165 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000166 };
167
168 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000169
Evan Chenga8e29892007-01-19 07:51:42 +0000170 /// WaterList - A sorted list of basic blocks where islands could be placed
171 /// (i.e. blocks that don't fall through to the following block, due
172 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000173 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000174
Bob Wilsonb9239532009-10-15 20:49:47 +0000175 /// NewWaterList - The subset of WaterList that was created since the
176 /// previous iteration by inserting unconditional branches.
177 SmallSet<MachineBasicBlock*, 4> NewWaterList;
178
Bob Wilson034de5f2009-10-12 18:52:13 +0000179 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
180
Evan Chenga8e29892007-01-19 07:51:42 +0000181 /// CPUser - One user of a constant pool, keeping the machine instruction
182 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000183 /// allowed from the instruction to the CP. The HighWaterMark records the
184 /// highest basic block where a new CPEntry can be placed. To ensure this
185 /// pass terminates, the CP entries are initially placed at the end of the
186 /// function and then move monotonically to lower addresses. The
187 /// exception to this rule is when the current CP entry for a particular
188 /// CPUser is out of range, but there is another CP entry for the same
189 /// constant value in range. We want to use the existing in-range CP
190 /// entry, but if it later moves out of range, the search for new water
191 /// should resume where it left off. The HighWaterMark is used to record
192 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000193 struct CPUser {
194 MachineInstr *MI;
195 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000196 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000197 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000198 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000199 bool IsSoImm;
200 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
201 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000202 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
203 HighWaterMark = CPEMI->getParent();
204 }
Evan Chenga8e29892007-01-19 07:51:42 +0000205 };
Bob Wilson84945262009-05-12 17:09:30 +0000206
Evan Chenga8e29892007-01-19 07:51:42 +0000207 /// CPUsers - Keep track of all of the machine instructions that use various
208 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000209 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000210
Evan Chengc99ef082007-02-09 20:54:44 +0000211 /// CPEntry - One per constant pool entry, keeping the machine instruction
212 /// pointer, the constpool index, and the number of CPUser's which
213 /// reference this entry.
214 struct CPEntry {
215 MachineInstr *CPEMI;
216 unsigned CPI;
217 unsigned RefCount;
218 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
219 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
220 };
221
222 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000223 /// instructions. For each original constpool index (i.e. those that
224 /// existed upon entry to this pass), it keeps a vector of entries.
225 /// Original elements are cloned as we go along; the clones are
226 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000227 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000228
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000229 /// ImmBranch - One per immediate branch, keeping the machine instruction
230 /// pointer, conditional or unconditional, the max displacement,
231 /// and (if isCond is true) the corresponding unconditional branch
232 /// opcode.
233 struct ImmBranch {
234 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000235 unsigned MaxDisp : 31;
236 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000237 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000238 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
239 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000240 };
241
Evan Cheng2706f972007-05-16 05:14:06 +0000242 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000243 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000244 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000245
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000246 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
247 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000248 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000249
Evan Cheng5657c012009-07-29 02:18:14 +0000250 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
251 SmallVector<MachineInstr*, 4> T2JumpTables;
252
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000253 /// HasFarJump - True if any far jump instruction has been emitted during
254 /// the branch fix up pass.
255 bool HasFarJump;
256
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000257 MachineFunction *MF;
258 MachineConstantPool *MCP;
Chris Lattner20628752010-07-22 21:27:00 +0000259 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000260 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000261 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000262 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000263 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000264 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000265 public:
Devang Patel19974732007-05-03 01:11:54 +0000266 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000267 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000268
Evan Cheng5657c012009-07-29 02:18:14 +0000269 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000270
271 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000272 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000273 }
Bob Wilson84945262009-05-12 17:09:30 +0000274
Evan Chenga8e29892007-01-19 07:51:42 +0000275 private:
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000276 void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000277 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000278 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000279 void JumpTableFunctionScan();
280 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000281 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000282 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000283 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000284 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000285 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000286 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000287 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000288 MachineBasicBlock *&NewMBB);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000289 bool HandleConstantPoolUser(unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000290 void RemoveDeadCPEMI(MachineInstr *CPEMI);
291 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000292 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000293 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
294 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000295 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000296 CPUser &U, unsigned &Growth);
Evan Chengc0dbec72007-01-31 19:57:44 +0000297 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000298 bool FixUpImmediateBr(ImmBranch &Br);
299 bool FixUpConditionalBr(ImmBranch &Br);
300 bool FixUpUnconditionalBr(ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000301 bool UndoLRSpillRestore();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000302 bool OptimizeThumb2Instructions();
303 bool OptimizeThumb2Branches();
304 bool ReorderThumb2JumpTables();
305 bool OptimizeThumb2JumpTables();
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000306 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
307 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000308
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000309 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000310 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000311 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000312 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000313
314 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
315 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
316 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
317 const CPUser &U) {
318 return OffsetIsInRange(UserOffset, TrialOffset,
319 U.MaxDisp, U.NegOk, U.IsSoImm);
320 }
Evan Chenga8e29892007-01-19 07:51:42 +0000321 };
Devang Patel19974732007-05-03 01:11:54 +0000322 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000323}
324
Dale Johannesen8593e412007-04-29 19:19:30 +0000325/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000326void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000327#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000328 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000329 MBBI != E; ++MBBI) {
330 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000331 unsigned Align = MBB->getAlignment();
332 unsigned MBBId = MBB->getNumber();
333 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
334 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000335 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000336 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
337 CPUser &U = CPUsers[i];
338 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000339 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
340 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
341 UserOffset - CPEOffset;
342 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000343 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000344#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000345}
346
347/// print block size and offset information - debugging
348void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000349 DEBUG({
350 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
351 const BasicBlockInfo &BBI = BBInfo[J];
352 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
353 << " kb=" << unsigned(BBI.KnownBits)
354 << " ua=" << unsigned(BBI.Unalign)
355 << " pa=" << unsigned(BBI.PostAlign)
356 << format(" size=%#x\n", BBInfo[J].Size);
357 }
358 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000359}
360
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000361/// createARMConstantIslandPass - returns an instance of the constpool
362/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000363FunctionPass *llvm::createARMConstantIslandPass() {
364 return new ARMConstantIslands();
365}
366
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000367bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
368 MF = &mf;
369 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000370
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000371 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000372 << MCP->getConstants().size() << " CP entries, aligned to "
373 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000374
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000375 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
376 AFI = MF->getInfo<ARMFunctionInfo>();
377 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000378
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000379 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000380 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000381 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000382
383 HasFarJump = false;
384
Evan Chenga8e29892007-01-19 07:51:42 +0000385 // Renumber all of the machine basic blocks in the function, guaranteeing that
386 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000387 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000388
Jim Grosbach80697d12009-11-12 17:25:07 +0000389 // Try to reorder and otherwise adjust the block layout to make good use
390 // of the TB[BH] instructions.
391 bool MadeChange = false;
392 if (isThumb2 && AdjustJumpTableBlocks) {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000393 JumpTableFunctionScan();
394 MadeChange |= ReorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000395 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000396 T2JumpTables.clear();
397 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000398 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000399 }
400
Evan Chengd26b14c2009-07-31 18:28:05 +0000401 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000402 // This is so we can keep exact track of where the alignment padding goes.
403
Chris Lattner7d7dab02010-01-27 23:37:36 +0000404 // ARM and Thumb2 functions need to be 4-byte aligned.
405 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000406 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000407
Evan Chenga8e29892007-01-19 07:51:42 +0000408 // Perform the initial placement of the constant pool entries. To start with,
409 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000410 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000411 if (!MCP->isEmpty())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000412 DoInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000413
Evan Chenga8e29892007-01-19 07:51:42 +0000414 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000415 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000416
Evan Chenga8e29892007-01-19 07:51:42 +0000417 // Do the initial scan of the function, building up information about the
418 // sizes of each block, the location of all the water, and finding all of the
419 // constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000420 InitialFunctionScan(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000421 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000422 DEBUG(dumpBBs());
423
Bob Wilson84945262009-05-12 17:09:30 +0000424
Evan Chenged884f32007-04-03 23:39:48 +0000425 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000426 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000427
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000428 // Iteratively place constant pool entries and fix up branches until there
429 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000430 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000431 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000432 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000433 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000434 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000435 CPChange |= HandleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000436 if (CPChange && ++NoCPIters > 30)
437 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000438 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000439
Bob Wilsonb9239532009-10-15 20:49:47 +0000440 // Clear NewWaterList now. If we split a block for branches, it should
441 // appear as "new water" for the next iteration of constant pool placement.
442 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000443
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000444 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000445 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000446 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000447 BRChange |= FixUpImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000448 if (BRChange && ++NoBRIters > 30)
449 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000450 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000451
452 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000453 break;
454 MadeChange = true;
455 }
Evan Chenged884f32007-04-03 23:39:48 +0000456
Evan Chenga1efbbd2009-08-14 00:32:16 +0000457 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000458 if (isThumb2 && !STI->prefers32BitThumb())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000459 MadeChange |= OptimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000460
Dale Johannesen8593e412007-04-29 19:19:30 +0000461 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000462 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000463
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000464 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
465 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000466 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000467 MadeChange |= UndoLRSpillRestore();
468
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000469 // Save the mapping between original and cloned constpool entries.
470 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
471 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
472 const CPEntry & CPE = CPEntries[i][j];
473 AFI->recordCPEClone(i, CPE.CPI);
474 }
475 }
476
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000477 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000478
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000479 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000480 WaterList.clear();
481 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000482 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000483 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000484 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000485 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000486
487 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000488}
489
490/// DoInitialPlacement - Perform the initial placement of the constant pool
491/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000492void
493ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000494 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000495 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
496 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000497
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000498 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000499 unsigned MaxAlign = Log2_32(MF->getConstantPool()->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000500
501 // Mark the basic block as required by the const-pool.
502 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
503 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
504
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000505 // The function needs to be as aligned as the basic blocks. The linker may
506 // move functions around based on their alignment.
507 MF->EnsureAlignment(BB->getAlignment());
508
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000509 // Order the entries in BB by descending alignment. That ensures correct
510 // alignment of all entries as long as BB is sufficiently aligned. Keep
511 // track of the insertion point for each alignment. We are going to bucket
512 // sort the entries as they are created.
513 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000514
Evan Chenga8e29892007-01-19 07:51:42 +0000515 // Add all of the constants from the constant pool to the end block, use an
516 // identity mapping of CPI's to CPE's.
517 const std::vector<MachineConstantPoolEntry> &CPs =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000518 MF->getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000519
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000520 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000521 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000522 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000523 assert(Size >= 4 && "Too small constant pool entry");
524 unsigned Align = CPs[i].getAlignment();
525 assert(isPowerOf2_32(Align) && "Invalid alignment");
526 // Verify that all constant pool entries are a multiple of their alignment.
527 // If not, we would have to pad them out so that instructions stay aligned.
528 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
529
530 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
531 unsigned LogAlign = Log2_32(Align);
532 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000533 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000534 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000535 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000536 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000537
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000538 // Ensure that future entries with higher alignment get inserted before
539 // CPEMI. This is bucket sort with iterators.
540 for (unsigned a = LogAlign + 1; a < MaxAlign; ++a)
541 if (InsPoint[a] == InsAt)
542 InsPoint[a] = CPEMI;
543
Evan Chengc99ef082007-02-09 20:54:44 +0000544 // Add a new CPEntry, but no corresponding CPUser yet.
545 std::vector<CPEntry> CPEs;
546 CPEs.push_back(CPEntry(CPEMI, i));
547 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000548 ++NumCPEs;
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000549 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000550 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000551 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000552}
553
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000554/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000555/// into the block immediately after it.
556static bool BBHasFallthrough(MachineBasicBlock *MBB) {
557 // Get the next machine basic block in the function.
558 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000559 // Can't fall off end of function.
560 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000561 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000562
Chris Lattner7896c9f2009-12-03 00:50:42 +0000563 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000564 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
565 E = MBB->succ_end(); I != E; ++I)
566 if (*I == NextBB)
567 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000568
Evan Chenga8e29892007-01-19 07:51:42 +0000569 return false;
570}
571
Evan Chengc99ef082007-02-09 20:54:44 +0000572/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
573/// look up the corresponding CPEntry.
574ARMConstantIslands::CPEntry
575*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
576 const MachineInstr *CPEMI) {
577 std::vector<CPEntry> &CPEs = CPEntries[CPI];
578 // Number of entries per constpool index should be small, just do a
579 // linear search.
580 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
581 if (CPEs[i].CPEMI == CPEMI)
582 return &CPEs[i];
583 }
584 return NULL;
585}
586
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000587/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000588/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000589unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
590 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
591
592 // Everything is 4-byte aligned unless AlignConstantIslands is set.
593 if (!AlignConstantIslands)
594 return 2;
595
596 unsigned CPI = CPEMI->getOperand(1).getIndex();
597 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
598 unsigned Align = MCP->getConstants()[CPI].getAlignment();
599 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
600 return Log2_32(Align);
601}
602
Jim Grosbach80697d12009-11-12 17:25:07 +0000603/// JumpTableFunctionScan - Do a scan of the function, building up
604/// information about the sizes of each block and the locations of all
605/// the jump tables.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000606void ARMConstantIslands::JumpTableFunctionScan() {
607 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000608 MBBI != E; ++MBBI) {
609 MachineBasicBlock &MBB = *MBBI;
610
Jim Grosbach80697d12009-11-12 17:25:07 +0000611 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000612 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000613 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000614 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000615 }
616}
617
Evan Chenga8e29892007-01-19 07:51:42 +0000618/// InitialFunctionScan - Do the initial scan of the function, building up
619/// information about the sizes of each block, the location of all the water,
620/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000621void ARMConstantIslands::
622InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000623 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000624 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000625
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000626 // First thing, compute the size of all basic blocks, and see if the function
627 // has any inline assembly in it. If so, we have to be conservative about
628 // alignment assumptions, as we don't know for sure the size of any
629 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000630 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000631 ComputeBlockSize(I);
632
633 // The known bits of the entry block offset are determined by the function
634 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000635 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000636
637 // Compute block offsets and known bits.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000638 AdjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000639
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000640 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000641 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000642 MBBI != E; ++MBBI) {
643 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000644
Evan Chenga8e29892007-01-19 07:51:42 +0000645 // If this block doesn't fall through into the next MBB, then this is
646 // 'water' that a constant pool island could be placed.
647 if (!BBHasFallthrough(&MBB))
648 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000649
Evan Chenga8e29892007-01-19 07:51:42 +0000650 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
651 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000652 if (I->isDebugValue())
653 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000654
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000655 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000656 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000657 bool isCond = false;
658 unsigned Bits = 0;
659 unsigned Scale = 1;
660 int UOpc = Opc;
661 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000662 default:
663 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000664 case ARM::t2BR_JT:
665 T2JumpTables.push_back(I);
666 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000667 case ARM::Bcc:
668 isCond = true;
669 UOpc = ARM::B;
670 // Fallthrough
671 case ARM::B:
672 Bits = 24;
673 Scale = 4;
674 break;
675 case ARM::tBcc:
676 isCond = true;
677 UOpc = ARM::tB;
678 Bits = 8;
679 Scale = 2;
680 break;
681 case ARM::tB:
682 Bits = 11;
683 Scale = 2;
684 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000685 case ARM::t2Bcc:
686 isCond = true;
687 UOpc = ARM::t2B;
688 Bits = 20;
689 Scale = 2;
690 break;
691 case ARM::t2B:
692 Bits = 24;
693 Scale = 2;
694 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000695 }
Evan Chengb43216e2007-02-01 10:16:15 +0000696
697 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000698 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000699 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000700 }
701
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000702 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
703 PushPopMIs.push_back(I);
704
Evan Chengd3d9d662009-07-23 18:27:47 +0000705 if (Opc == ARM::CONSTPOOL_ENTRY)
706 continue;
707
Evan Chenga8e29892007-01-19 07:51:42 +0000708 // Scan the instructions for constant pool operands.
709 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000710 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000711 // We found one. The addressing mode tells us the max displacement
712 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000713
Evan Chenga8e29892007-01-19 07:51:42 +0000714 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000715 unsigned Bits = 0;
716 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000717 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000718 bool IsSoImm = false;
719
720 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000721 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000722 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000723 break;
724
725 // Taking the address of a CP entry.
726 case ARM::LEApcrel:
727 // This takes a SoImm, which is 8 bit immediate rotated. We'll
728 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000729 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000730 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000731 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000732 Scale = 4;
733 NegOk = true;
734 IsSoImm = true;
735 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000736 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000737 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000738 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000739 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000740 case ARM::tLEApcrel:
741 Bits = 8;
742 Scale = 4;
743 break;
744
Jim Grosbach3e556122010-10-26 22:37:02 +0000745 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000746 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000747 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000748 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000749 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000750 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000751
752 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000753 Bits = 8;
754 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000755 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000756
Jim Grosbache5165492009-11-09 00:11:35 +0000757 case ARM::VLDRD:
758 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000759 Bits = 8;
760 Scale = 4; // +-(offset_8*4)
761 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000762 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000763 }
Evan Chengb43216e2007-02-01 10:16:15 +0000764
Evan Chenga8e29892007-01-19 07:51:42 +0000765 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000766 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000767 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000768 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000769 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000770
771 // Increment corresponding CPEntry reference count.
772 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
773 assert(CPE && "Cannot find a corresponding CPEntry!");
774 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000775
Evan Chenga8e29892007-01-19 07:51:42 +0000776 // Instructions can only use one CP entry, don't bother scanning the
777 // rest of the operands.
778 break;
779 }
780 }
Evan Chenga8e29892007-01-19 07:51:42 +0000781 }
782}
783
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000784/// ComputeBlockSize - Compute the size and some alignment information for MBB.
785/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000786void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000787 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
788 BBI.Size = 0;
789 BBI.Unalign = 0;
790 BBI.PostAlign = 0;
791
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000792 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
793 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000794 BBI.Size += TII->GetInstSizeInBytes(I);
795 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
796 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000797 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000798 BBI.Unalign = isThumb ? 1 : 2;
799 }
800
801 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000802 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000803 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000804 MBB->getParent()->EnsureAlignment(2);
805 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000806}
807
Evan Chenga8e29892007-01-19 07:51:42 +0000808/// GetOffsetOf - Return the current offset of the specified machine instruction
809/// from the start of the function. This offset changes as stuff is moved
810/// around inside the function.
811unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
812 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000813
Evan Chenga8e29892007-01-19 07:51:42 +0000814 // The offset is composed of two things: the sum of the sizes of all MBB's
815 // before this instruction's block, and the offset from the start of the block
816 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000817 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000818
819 // Sum instructions before MI in MBB.
820 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
821 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
822 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000823 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000824 }
825}
826
827/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
828/// ID.
829static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
830 const MachineBasicBlock *RHS) {
831 return LHS->getNumber() < RHS->getNumber();
832}
833
834/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
835/// machine function, it upsets all of the block numbers. Renumber the blocks
836/// and update the arrays that parallel this numbering.
837void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000838 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000839 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000840
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000841 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000842 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000843 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000844
845 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000846 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000847 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000848 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
849 CompareMBBNumbers);
850 WaterList.insert(IP, NewBB);
851}
852
853
854/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000855/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000856/// account for this change and returns the newly created block.
857MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000858 MachineBasicBlock *OrigBB = MI->getParent();
859
860 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000861 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000862 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000863 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000864 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000865
Evan Chenga8e29892007-01-19 07:51:42 +0000866 // Splice the instructions starting with MI over to NewBB.
867 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000868
Evan Chenga8e29892007-01-19 07:51:42 +0000869 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000870 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000871 // There doesn't seem to be meaningful DebugInfo available; this doesn't
872 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000873 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000874 if (!isThumb)
875 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
876 else
877 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
878 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000879 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000880
Evan Chenga8e29892007-01-19 07:51:42 +0000881 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000882 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000883
Evan Chenga8e29892007-01-19 07:51:42 +0000884 // OrigBB branches to NewBB.
885 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000886
Evan Chenga8e29892007-01-19 07:51:42 +0000887 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888 // This is almost the same as UpdateForInsertedWaterBlock, except that
889 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000890 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000891
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000892 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000893 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000894 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000895
Bob Wilson84945262009-05-12 17:09:30 +0000896 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000897 // available water after it (but not if it's already there, which happens
898 // when splitting before a conditional branch that is followed by an
899 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000900 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
902 CompareMBBNumbers);
903 MachineBasicBlock* WaterBB = *IP;
904 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000905 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906 else
907 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000908 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000909
Dale Johannesen8086d582010-07-23 22:50:23 +0000910 // Figure out how large the OrigBB is. As the first half of the original
911 // block, it cannot contain a tablejump. The size includes
912 // the new jump we added. (It should be possible to do this without
913 // recounting everything, but it's very confusing, and this is rarely
914 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000915 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000916
Dale Johannesen8086d582010-07-23 22:50:23 +0000917 // Figure out how large the NewMBB is. As the second half of the original
918 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000919 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000920
Dale Johannesen99c49a42007-02-25 00:47:03 +0000921 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000922 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000923
924 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000925}
926
Dale Johannesen8593e412007-04-29 19:19:30 +0000927/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000928/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000929/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000930bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000931 unsigned TrialOffset, unsigned MaxDisp,
932 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000933 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
934 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000935 // Effectively, the valid range of displacements is 2 bytes smaller for such
936 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000937 unsigned TotalAdj = 0;
938 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000939 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000940 TotalAdj = 2;
941 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000942 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000943 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000944 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000945 TotalAdj += 2;
946 }
947
948 // In Thumb2 mode, later branch adjustments can shift instructions up and
949 // cause alignment change. In the worst case scenario this can cause the
950 // user's effective address to be subtracted by 2 and the CPE's address to
951 // be plus 2.
952 if (isThumb2 && TotalAdj != 4)
953 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000954
Dale Johannesen99c49a42007-02-25 00:47:03 +0000955 if (UserOffset <= TrialOffset) {
956 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000957 if (TrialOffset - UserOffset <= MaxDisp)
958 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000959 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000960 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000961 if (UserOffset - TrialOffset <= MaxDisp)
962 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000963 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000964 }
965 return false;
966}
967
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000968/// WaterIsInRange - Returns true if a CPE placed after the specified
969/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000970///
971/// Compute how much the function will grow by inserting a CPE after Water.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000972bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000973 MachineBasicBlock* Water, CPUser &U,
974 unsigned &Growth) {
975 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
976 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
977 unsigned NextBlockOffset, NextBlockAlignment;
978 MachineFunction::const_iterator NextBlock = Water;
979 if (++NextBlock == MF->end()) {
980 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
981 NextBlockAlignment = 0;
982 } else {
983 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
984 NextBlockAlignment = NextBlock->getAlignment();
985 }
986 unsigned Size = U.CPEMI->getOperand(2).getImm();
987 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000988
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000989 // The CPE may be able to hide in the alignment padding before the next
990 // block. It may also cause more padding to be required if it is more aligned
991 // that the next block.
992 if (CPEEnd > NextBlockOffset) {
993 Growth = CPEEnd - NextBlockOffset;
994 // Compute the padding that would go at the end of the CPE to align the next
995 // block.
996 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
997
998 // If the CPE is to be inserted before the instruction, that will raise
999 // the offset of the instruction. Also account for unknown alignment padding
1000 // in blocks between CPE and the user.
1001 if (CPEOffset < UserOffset)
1002 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1003 } else
1004 // CPE fits in existing padding.
1005 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001006
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001007 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001008}
1009
1010/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001011/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001012bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001013 MachineInstr *CPEMI, unsigned MaxDisp,
1014 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001015 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +00001016 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +00001017
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001018 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001019 DEBUG({
1020 unsigned Block = MI->getParent()->getNumber();
1021 const BasicBlockInfo &BBI = BBInfo[Block];
1022 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1023 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001024 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001025 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001026 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1027 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1028 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001029 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001030 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001031
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001032 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001033}
1034
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001035#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001036/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1037/// unconditionally branches to its only successor.
1038static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1039 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1040 return false;
1041
1042 MachineBasicBlock *Succ = *MBB->succ_begin();
1043 MachineBasicBlock *Pred = *MBB->pred_begin();
1044 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001045 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1046 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001047 return PredMI->getOperand(0).getMBB() == Succ;
1048 return false;
1049}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001050#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001051
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001052void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001053 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1054 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001055 // Include the alignment of the current block.
1056 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1057 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1058 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001059
1060 // This is where block i begins.
1061 BBInfo[i].Offset = Offset;
1062 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001063 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001064}
1065
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001066/// DecrementOldEntry - find the constant pool entry with index CPI
1067/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001068/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001069/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001070
Evan Chenged884f32007-04-03 23:39:48 +00001071bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001072 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001073 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1074 assert(CPE && "Unexpected!");
1075 if (--CPE->RefCount == 0) {
1076 RemoveDeadCPEMI(CPEMI);
1077 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001078 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001079 return true;
1080 }
1081 return false;
1082}
1083
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001084/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1085/// if not, see if an in-range clone of the CPE is in range, and if so,
1086/// change the data structures so the user references the clone. Returns:
1087/// 0 = no existing entry found
1088/// 1 = entry found, and there were no code insertions or deletions
1089/// 2 = entry found, and there were code insertions or deletions
1090int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1091{
1092 MachineInstr *UserMI = U.MI;
1093 MachineInstr *CPEMI = U.CPEMI;
1094
1095 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001096 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001097 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001098 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001099 }
1100
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001102 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001103 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1104 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1105 // We already tried this one
1106 if (CPEs[i].CPEMI == CPEMI)
1107 continue;
1108 // Removing CPEs can leave empty entries, skip
1109 if (CPEs[i].CPEMI == NULL)
1110 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001111 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001112 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001113 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001114 // Point the CPUser node to the replacement
1115 U.CPEMI = CPEs[i].CPEMI;
1116 // Change the CPI in the instruction operand to refer to the clone.
1117 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001118 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001119 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001120 break;
1121 }
1122 // Adjust the refcount of the clone...
1123 CPEs[i].RefCount++;
1124 // ...and the original. If we didn't remove the old entry, none of the
1125 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001126 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001127 }
1128 }
1129 return 0;
1130}
1131
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001132/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1133/// the specific unconditional branch instruction.
1134static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001135 switch (Opc) {
1136 case ARM::tB:
1137 return ((1<<10)-1)*2;
1138 case ARM::t2B:
1139 return ((1<<23)-1)*2;
1140 default:
1141 break;
1142 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001143
David Goodwin5e47a9a2009-06-30 18:04:13 +00001144 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001145}
1146
Bob Wilsonb9239532009-10-15 20:49:47 +00001147/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001148/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001149/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001150/// is set to the WaterList entry. For Thumb, prefer water that will not
1151/// introduce padding to water that will. To ensure that this pass
1152/// terminates, the CPE location for a particular CPUser is only allowed to
1153/// move to a lower address, so search backward from the end of the list and
1154/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001155bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001156 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001157 if (WaterList.empty())
1158 return false;
1159
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001160 unsigned BestGrowth = ~0u;
1161 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1162 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001163 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001164 // Check if water is in range and is either at a lower address than the
1165 // current "high water mark" or a new water block that was created since
1166 // the previous iteration by inserting an unconditional branch. In the
1167 // latter case, we want to allow resetting the high water mark back to
1168 // this new water since we haven't seen it before. Inserting branches
1169 // should be relatively uncommon and when it does happen, we want to be
1170 // sure to take advantage of it for all the CPEs near that block, so that
1171 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001172 unsigned Growth;
1173 if (WaterIsInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001174 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001175 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1176 // This is the least amount of required padding seen so far.
1177 BestGrowth = Growth;
1178 WaterIter = IP;
1179 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1180 << " Growth=" << Growth << '\n');
1181
1182 // Keep looking unless it is perfect.
1183 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001184 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001185 }
Bob Wilson3b757352009-10-12 19:04:03 +00001186 if (IP == B)
1187 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001188 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001189 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001190}
1191
Bob Wilson84945262009-05-12 17:09:30 +00001192/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001193/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1194/// block is used if in range, and the conditional branch munged so control
1195/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001196/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001197/// block following which the new island can be inserted (the WaterList
1198/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001199void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001200 unsigned UserOffset,
1201 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001202 CPUser &U = CPUsers[CPUserIndex];
1203 MachineInstr *UserMI = U.MI;
1204 MachineInstr *CPEMI = U.CPEMI;
1205 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001206 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1207 unsigned OffsetOfNextBlock = UserBBI.postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001208
Bob Wilson36fa5322009-10-15 05:10:36 +00001209 // If the block does not end in an unconditional branch already, and if the
1210 // end of the block is within range, make new water there. (The addition
1211 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1212 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001213 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001214 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001215 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001216 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001217 if (&UserMBB->back() == UserMI)
1218 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001219 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001220 // Add an unconditional branch from UserMBB to fallthrough block.
1221 // Record it for branch lengthening; this new branch will not get out of
1222 // range, but if the preceding conditional branch is out of range, the
1223 // targets will be exchanged, and the altered branch may be out of
1224 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001225 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001226 if (!isThumb)
1227 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1228 else
1229 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1230 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001231 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001232 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001233 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001234 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001235 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001236 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001237 } else {
1238 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001239 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001240 // and constant pool entries are 4 bytes: if instruction I references
1241 // island CPE, and instruction I+1 references CPE', it will
1242 // not work well to put CPE as far forward as possible, since then
1243 // CPE' cannot immediately follow it (that location is 2 bytes
1244 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001245 // a new island. So, we make a first guess, then walk through the
1246 // instructions between the one currently being looked at and the
1247 // possible insertion point, and make sure any other instructions
1248 // that reference CPEs will be able to use the same island area;
1249 // if not, we back up the insertion point.
1250
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001251 // Try to split the block so it's fully aligned. Compute the latest split
1252 // point where we can add a 4-byte branch instruction, and then
1253 // WorstCaseAlign to LogAlign.
1254 unsigned LogAlign = UserMBB->getParent()->getAlignment();
1255 unsigned KnownBits = UserBBI.internalKnownBits();
1256 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1257 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1258 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1259 BaseInsertOffset));
1260
1261 // Account for alignment and unknown padding.
1262 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1263 BaseInsertOffset -= UPad;
1264
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001265 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001266 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001267 // island is handled inside OffsetIsInRange.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001268 BaseInsertOffset -= 4;
1269
1270 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1271 << " la=" << LogAlign
1272 << " kb=" << KnownBits
1273 << " up=" << UPad << '\n');
1274
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001275 // This could point off the end of the block if we've already got
1276 // constant pool entries following this block; only the last one is
1277 // in the water list. Back past any possible branches (allow for a
1278 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001279 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1280 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001281 (isThumb1 ? 6 : 8);
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001282 unsigned EndInsertOffset =
1283 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1284 CPEMI->getOperand(2).getImm();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001285 MachineBasicBlock::iterator MI = UserMI;
1286 ++MI;
1287 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001288 unsigned NumCPUsers = CPUsers.size();
1289 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001290 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001291 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001292 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001293 MI = llvm::next(MI)) {
1294 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001295 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001296 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001297 BaseInsertOffset -= 1u << LogAlign;
1298 EndInsertOffset -= 1u << LogAlign;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001299 }
1300 // This is overly conservative, as we don't account for CPEMIs
1301 // being reused within the block, but it doesn't matter much.
1302 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1303 CPUIndex++;
1304 }
Evan Cheng719510a2010-08-12 20:30:05 +00001305
1306 // Remember the last IT instruction.
1307 if (MI->getOpcode() == ARM::t2IT)
1308 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001309 }
Evan Cheng719510a2010-08-12 20:30:05 +00001310
Evan Cheng719510a2010-08-12 20:30:05 +00001311 --MI;
1312
1313 // Avoid splitting an IT block.
1314 if (LastIT) {
1315 unsigned PredReg = 0;
1316 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1317 if (CC != ARMCC::AL)
1318 MI = LastIT;
1319 }
1320 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001321 }
1322}
1323
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001324/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001325/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001326/// place in-range. Return true if we changed any addresses (thus must run
1327/// another pass of branch lengthening), false otherwise.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001328bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001329 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001330 MachineInstr *UserMI = U.MI;
1331 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001332 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001333 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001334 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001335 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001336 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001337
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001338 // See if the current entry is within range, or there is a clone of it
1339 // in range.
1340 int result = LookForExistingCPEntry(U, UserOffset);
1341 if (result==1) return false;
1342 else if (result==2) return true;
1343
1344 // No existing clone of this CPE is within range.
1345 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001346 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001347
Bob Wilsonf98032e2009-10-12 21:23:15 +00001348 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001349 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001350 MachineBasicBlock *NewMBB;
1351 water_iterator IP;
1352 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001353 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001354 MachineBasicBlock *WaterBB = *IP;
1355
1356 // If the original WaterList entry was "new water" on this iteration,
1357 // propagate that to the new island. This is just keeping NewWaterList
1358 // updated to match the WaterList, which will be updated below.
1359 if (NewWaterList.count(WaterBB)) {
1360 NewWaterList.erase(WaterBB);
1361 NewWaterList.insert(NewIsland);
1362 }
1363 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001364 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001365
1366 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001367 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001368 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001369 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001370
1371 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1372 // called while handling branches so that the water will be seen on the
1373 // next iteration for constant pools, but in this context, we don't want
1374 // it. Check for this so it will be removed from the WaterList.
1375 // Also remove any entry from NewWaterList.
1376 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1377 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1378 if (IP != WaterList.end())
1379 NewWaterList.erase(WaterBB);
1380
1381 // We are adding new water. Update NewWaterList.
1382 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001383 }
1384
Bob Wilsonb9239532009-10-15 20:49:47 +00001385 // Remove the original WaterList entry; we want subsequent insertions in
1386 // this vicinity to go after the one we're about to insert. This
1387 // considerably reduces the number of times we have to move the same CPE
1388 // more than once and is also important to ensure the algorithm terminates.
1389 if (IP != WaterList.end())
1390 WaterList.erase(IP);
1391
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001392 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001393 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001394
1395 // Update internal data structures to account for the newly inserted MBB.
1396 UpdateForInsertedWaterBlock(NewIsland);
1397
1398 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001399 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001400
1401 // Now that we have an island to add the CPE to, clone the original CPE and
1402 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001403 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001404 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001405 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001406 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001407 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001408
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001409 // Mark the basic block as aligned as required by the const-pool entry.
1410 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001411
Evan Chenga8e29892007-01-19 07:51:42 +00001412 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001413 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001414 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001415
Evan Chenga8e29892007-01-19 07:51:42 +00001416 // Finally, change the CPI in the instruction operand to be ID.
1417 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001418 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001419 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001420 break;
1421 }
Bob Wilson84945262009-05-12 17:09:30 +00001422
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001423 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001424 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001425
Evan Chenga8e29892007-01-19 07:51:42 +00001426 return true;
1427}
1428
Evan Chenged884f32007-04-03 23:39:48 +00001429/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1430/// sizes and offsets of impacted basic blocks.
1431void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1432 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001433 unsigned Size = CPEMI->getOperand(2).getImm();
1434 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001435 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001436 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001437 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001438 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001439
1440 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1441 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001442 } else
1443 // Entries are sorted by descending alignment, so realign from the front.
1444 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1445
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001446 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001447 // An island has only one predecessor BB and one successor BB. Check if
1448 // this BB's predecessor jumps directly to this BB's successor. This
1449 // shouldn't happen currently.
1450 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1451 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001452}
1453
1454/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1455/// are zero.
1456bool ARMConstantIslands::RemoveUnusedCPEntries() {
1457 unsigned MadeChange = false;
1458 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1459 std::vector<CPEntry> &CPEs = CPEntries[i];
1460 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1461 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1462 RemoveDeadCPEMI(CPEs[j].CPEMI);
1463 CPEs[j].CPEMI = NULL;
1464 MadeChange = true;
1465 }
1466 }
Bob Wilson84945262009-05-12 17:09:30 +00001467 }
Evan Chenged884f32007-04-03 23:39:48 +00001468 return MadeChange;
1469}
1470
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001471/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001472/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001473bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1474 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001475 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001476 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001477 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001478
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001479 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001480 << " from BB#" << MI->getParent()->getNumber()
1481 << " max delta=" << MaxDisp
1482 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1483 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001484
Dale Johannesen8593e412007-04-29 19:19:30 +00001485 if (BrOffset <= DestOffset) {
1486 // Branch before the Dest.
1487 if (DestOffset-BrOffset <= MaxDisp)
1488 return true;
1489 } else {
1490 if (BrOffset-DestOffset <= MaxDisp)
1491 return true;
1492 }
1493 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001494}
1495
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001496/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1497/// away to fit in its displacement field.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001498bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001499 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001500 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001501
Evan Chengc0dbec72007-01-31 19:57:44 +00001502 // Check to see if the DestBB is already in-range.
1503 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001504 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001505
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001506 if (!Br.isCond)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001507 return FixUpUnconditionalBr(Br);
1508 return FixUpConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001509}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001510
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001511/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1512/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001513/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001514/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001515bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001516ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001517 MachineInstr *MI = Br.MI;
1518 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001519 if (!isThumb1)
1520 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001521
1522 // Use BL to implement far jump.
1523 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001524 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001525 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001526 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001527 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001528 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001529
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001530 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001531
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001532 return true;
1533}
1534
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001535/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001536/// far away to fit in its displacement field. It is converted to an inverse
1537/// conditional branch + an unconditional branch to the destination.
1538bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001539ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001540 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001541 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001542
Bob Wilson39bf0512009-05-12 17:35:29 +00001543 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001544 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001545 // blt L1
1546 // =>
1547 // bge L2
1548 // b L1
1549 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001550 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001551 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001552 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001553
1554 // If the branch is at the end of its MBB and that has a fall-through block,
1555 // direct the updated conditional branch to the fall-through block. Otherwise,
1556 // split the MBB before the next instruction.
1557 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001558 MachineInstr *BMI = &MBB->back();
1559 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001560
Dan Gohmanfe601042010-06-22 15:08:57 +00001561 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001562 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001563 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001564 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001565 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001566 // condition and swap destinations:
1567 // beq L1
1568 // b L2
1569 // =>
1570 // bne L2
1571 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001572 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001573 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001574 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001575 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001576 BMI->getOperand(0).setMBB(DestBB);
1577 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001578 MI->getOperand(1).setImm(CC);
1579 return true;
1580 }
1581 }
1582 }
1583
1584 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001585 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001586 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001587 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001588 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001589 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001590 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001591 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001592 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001593 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001594
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001595 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001596 << " also invert condition and change dest. to BB#"
1597 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001598
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001599 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001600 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001601 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001602 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001603 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001604 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001605 if (isThumb)
1606 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1607 .addImm(ARMCC::AL).addReg(0);
1608 else
1609 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001610 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001611 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001612 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001613
1614 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001615 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001616 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001617 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001618 return true;
1619}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001620
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001621/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001622/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1623/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001624bool ARMConstantIslands::UndoLRSpillRestore() {
1625 bool MadeChange = false;
1626 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1627 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001628 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001629 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001630 MI->getOperand(2).getReg() == ARM::PC &&
1631 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001632 // Create the new insn and copy the predicate from the old.
1633 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1634 .addOperand(MI->getOperand(0))
1635 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001636 MI->eraseFromParent();
1637 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001638 }
1639 }
1640 return MadeChange;
1641}
Evan Cheng5657c012009-07-29 02:18:14 +00001642
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001643bool ARMConstantIslands::OptimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001644 bool MadeChange = false;
1645
1646 // Shrink ADR and LDR from constantpool.
1647 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1648 CPUser &U = CPUsers[i];
1649 unsigned Opcode = U.MI->getOpcode();
1650 unsigned NewOpc = 0;
1651 unsigned Scale = 1;
1652 unsigned Bits = 0;
1653 switch (Opcode) {
1654 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001655 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001656 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1657 NewOpc = ARM::tLEApcrel;
1658 Bits = 8;
1659 Scale = 4;
1660 }
1661 break;
1662 case ARM::t2LDRpci:
1663 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1664 NewOpc = ARM::tLDRpci;
1665 Bits = 8;
1666 Scale = 4;
1667 }
1668 break;
1669 }
1670
1671 if (!NewOpc)
1672 continue;
1673
1674 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1675 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1676 // FIXME: Check if offset is multiple of scale if scale is not 4.
1677 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1678 U.MI->setDesc(TII->get(NewOpc));
1679 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001680 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001681 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001682 ++NumT2CPShrunk;
1683 MadeChange = true;
1684 }
1685 }
1686
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001687 MadeChange |= OptimizeThumb2Branches();
1688 MadeChange |= OptimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001689 return MadeChange;
1690}
1691
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001692bool ARMConstantIslands::OptimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001693 bool MadeChange = false;
1694
1695 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1696 ImmBranch &Br = ImmBranches[i];
1697 unsigned Opcode = Br.MI->getOpcode();
1698 unsigned NewOpc = 0;
1699 unsigned Scale = 1;
1700 unsigned Bits = 0;
1701 switch (Opcode) {
1702 default: break;
1703 case ARM::t2B:
1704 NewOpc = ARM::tB;
1705 Bits = 11;
1706 Scale = 2;
1707 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001708 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001709 NewOpc = ARM::tBcc;
1710 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001711 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001712 break;
1713 }
Evan Chengde17fb62009-10-31 23:46:45 +00001714 }
1715 if (NewOpc) {
1716 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1717 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1718 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1719 Br.MI->setDesc(TII->get(NewOpc));
1720 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001721 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001722 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001723 ++NumT2BrShrunk;
1724 MadeChange = true;
1725 }
1726 }
1727
1728 Opcode = Br.MI->getOpcode();
1729 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001730 continue;
1731
Evan Chengde17fb62009-10-31 23:46:45 +00001732 NewOpc = 0;
1733 unsigned PredReg = 0;
1734 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1735 if (Pred == ARMCC::EQ)
1736 NewOpc = ARM::tCBZ;
1737 else if (Pred == ARMCC::NE)
1738 NewOpc = ARM::tCBNZ;
1739 if (!NewOpc)
1740 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001741 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001742 // Check if the distance is within 126. Subtract starting offset by 2
1743 // because the cmp will be eliminated.
1744 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001745 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001746 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001747 MachineBasicBlock::iterator CmpMI = Br.MI;
1748 if (CmpMI != Br.MI->getParent()->begin()) {
1749 --CmpMI;
1750 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1751 unsigned Reg = CmpMI->getOperand(0).getReg();
1752 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1753 if (Pred == ARMCC::AL &&
1754 CmpMI->getOperand(1).getImm() == 0 &&
1755 isARMLowRegister(Reg)) {
1756 MachineBasicBlock *MBB = Br.MI->getParent();
1757 MachineInstr *NewBR =
1758 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1759 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1760 CmpMI->eraseFromParent();
1761 Br.MI->eraseFromParent();
1762 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001763 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001764 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001765 ++NumCBZ;
1766 MadeChange = true;
1767 }
Evan Chengde17fb62009-10-31 23:46:45 +00001768 }
1769 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001770 }
1771 }
1772
1773 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001774}
1775
Evan Chenga1efbbd2009-08-14 00:32:16 +00001776/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1777/// jumptables when it's possible.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001778bool ARMConstantIslands::OptimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001779 bool MadeChange = false;
1780
1781 // FIXME: After the tables are shrunk, can we get rid some of the
1782 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001783 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001784 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001785
Evan Cheng5657c012009-07-29 02:18:14 +00001786 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1787 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1788 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001789 const MCInstrDesc &MCID = MI->getDesc();
1790 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001791 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001792 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1793 unsigned JTI = JTOP.getIndex();
1794 assert(JTI < JT.size());
1795
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001796 bool ByteOk = true;
1797 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001798 unsigned JTOffset = GetOffsetOf(MI) + 4;
1799 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001800 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1801 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001802 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001803 // Negative offset is not ok. FIXME: We should change BB layout to make
1804 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001805 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001806 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001807 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001808 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001809 HalfWordOk = false;
1810 if (!ByteOk && !HalfWordOk)
1811 break;
1812 }
1813
1814 if (ByteOk || HalfWordOk) {
1815 MachineBasicBlock *MBB = MI->getParent();
1816 unsigned BaseReg = MI->getOperand(0).getReg();
1817 bool BaseRegKill = MI->getOperand(0).isKill();
1818 if (!BaseRegKill)
1819 continue;
1820 unsigned IdxReg = MI->getOperand(1).getReg();
1821 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001822
1823 // Scan backwards to find the instruction that defines the base
1824 // register. Due to post-RA scheduling, we can't count on it
1825 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001826 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001827 MachineBasicBlock::iterator B = MBB->begin();
1828 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1829 --PrevI;
1830
1831 // If for some reason we didn't find it, we can't do anything, so
1832 // just skip this one.
1833 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001834 continue;
1835
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001836 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001837 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001838 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001839 // Make sure it only defines the base register and kills any uses
1840 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001841 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1842 const MachineOperand &MO = AddrMI->getOperand(k);
1843 if (!MO.isReg() || !MO.getReg())
1844 continue;
1845 if (MO.isDef() && MO.getReg() != BaseReg) {
1846 OptOk = false;
1847 break;
1848 }
1849 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1850 OptOk = false;
1851 break;
1852 }
1853 }
1854 if (!OptOk)
1855 continue;
1856
Owen Anderson6b8719f2010-12-13 22:51:08 +00001857 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001858 // that gave us the initial base register definition.
1859 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1860 ;
1861
Owen Anderson6b8719f2010-12-13 22:51:08 +00001862 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001863 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001864 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001865 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001866 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001867 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001868 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001869
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001870 if (!OptOk)
1871 continue;
1872
Jim Grosbachd092a872010-11-29 21:28:32 +00001873 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001874 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1875 .addReg(IdxReg, getKillRegState(IdxRegKill))
1876 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1877 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1878 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1879 // is 2-byte aligned. For now, asm printer will fix it up.
1880 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1881 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1882 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1883 OrigSize += TII->GetInstSizeInBytes(MI);
1884
1885 AddrMI->eraseFromParent();
1886 LeaMI->eraseFromParent();
1887 MI->eraseFromParent();
1888
1889 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001890 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001891 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001892
1893 ++NumTBs;
1894 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001895 }
1896 }
1897
1898 return MadeChange;
1899}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001900
Jim Grosbach9249efe2009-11-16 18:55:47 +00001901/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1902/// jump tables always branch forwards, since that's what tbb and tbh need.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001903bool ARMConstantIslands::ReorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001904 bool MadeChange = false;
1905
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001906 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001907 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001908
Jim Grosbach80697d12009-11-12 17:25:07 +00001909 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1910 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1911 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001912 const MCInstrDesc &MCID = MI->getDesc();
1913 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001914 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001915 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1916 unsigned JTI = JTOP.getIndex();
1917 assert(JTI < JT.size());
1918
1919 // We prefer if target blocks for the jump table come after the jump
1920 // instruction so we can use TB[BH]. Loop through the target blocks
1921 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001922 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001923 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1924 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1925 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001926 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001927
Jim Grosbach08cbda52009-11-16 18:58:52 +00001928 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001929 // The destination precedes the switch. Try to move the block forward
1930 // so we have a positive offset.
1931 MachineBasicBlock *NewBB =
1932 AdjustJTTargetBlockForward(MBB, MI->getParent());
1933 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001934 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001935 MadeChange = true;
1936 }
1937 }
1938 }
1939
1940 return MadeChange;
1941}
1942
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001943MachineBasicBlock *ARMConstantIslands::
1944AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1945{
Jim Grosbach03e2d442010-07-07 22:53:35 +00001946 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001947 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001948 // table that branches back to the actual target. This is a very simple
1949 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001950 MachineBasicBlock *TBB = 0, *FBB = 0;
1951 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001952 SmallVector<MachineOperand, 4> CondPrior;
1953 MachineFunction::iterator BBi = BB;
1954 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001955
Jim Grosbachca215e72009-11-16 17:10:56 +00001956 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001957 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001958
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001959 // If the block ends in an unconditional branch, move it. The prior block
1960 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001961 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001962 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001963 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001964 BB->moveAfter(JTBB);
1965 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001966 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001967 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001968 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001969 ++NumJTMoved;
1970 return NULL;
1971 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001972
1973 // Create a new MBB for the code after the jump BB.
1974 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001975 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001976 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001977 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001978
1979 // Add an unconditional branch from NewBB to BB.
1980 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1981 // correspond directly to anything in the source.
1982 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001983 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1984 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001985
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001986 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001987 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001988
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001989 // Update the CFG.
1990 NewBB->addSuccessor(BB);
1991 JTBB->removeSuccessor(BB);
1992 JTBB->addSuccessor(NewBB);
1993
Jim Grosbach80697d12009-11-12 17:25:07 +00001994 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001995 return NewBB;
1996}