blob: f81361fa7d6bd053567bb2206881386a41f4464a [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 Olesen5bb32532011-12-07 01:22:52 +0000145 /// Compute the offset immediately following this block.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000146 unsigned postOffset() const {
147 unsigned PO = Offset + Size;
148 if (!PostAlign)
149 return PO;
150 // Add alignment padding from the terminator.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000151 return WorstCaseAlign(PO, PostAlign, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000152 }
153
154 /// Compute the number of known low bits of postOffset. If this block
155 /// contains inline asm, the number of known bits drops to the
156 /// instruction alignment. An aligned terminator may increase the number
157 /// of know bits.
158 unsigned postKnownBits() const {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000159 return std::max(unsigned(PostAlign), internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000160 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000161 };
162
163 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000164
Evan Chenga8e29892007-01-19 07:51:42 +0000165 /// WaterList - A sorted list of basic blocks where islands could be placed
166 /// (i.e. blocks that don't fall through to the following block, due
167 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000168 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000169
Bob Wilsonb9239532009-10-15 20:49:47 +0000170 /// NewWaterList - The subset of WaterList that was created since the
171 /// previous iteration by inserting unconditional branches.
172 SmallSet<MachineBasicBlock*, 4> NewWaterList;
173
Bob Wilson034de5f2009-10-12 18:52:13 +0000174 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
175
Evan Chenga8e29892007-01-19 07:51:42 +0000176 /// CPUser - One user of a constant pool, keeping the machine instruction
177 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000178 /// allowed from the instruction to the CP. The HighWaterMark records the
179 /// highest basic block where a new CPEntry can be placed. To ensure this
180 /// pass terminates, the CP entries are initially placed at the end of the
181 /// function and then move monotonically to lower addresses. The
182 /// exception to this rule is when the current CP entry for a particular
183 /// CPUser is out of range, but there is another CP entry for the same
184 /// constant value in range. We want to use the existing in-range CP
185 /// entry, but if it later moves out of range, the search for new water
186 /// should resume where it left off. The HighWaterMark is used to record
187 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000188 struct CPUser {
189 MachineInstr *MI;
190 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000191 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000192 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000193 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000194 bool IsSoImm;
195 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
196 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000197 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
198 HighWaterMark = CPEMI->getParent();
199 }
Evan Chenga8e29892007-01-19 07:51:42 +0000200 };
Bob Wilson84945262009-05-12 17:09:30 +0000201
Evan Chenga8e29892007-01-19 07:51:42 +0000202 /// CPUsers - Keep track of all of the machine instructions that use various
203 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000204 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000205
Evan Chengc99ef082007-02-09 20:54:44 +0000206 /// CPEntry - One per constant pool entry, keeping the machine instruction
207 /// pointer, the constpool index, and the number of CPUser's which
208 /// reference this entry.
209 struct CPEntry {
210 MachineInstr *CPEMI;
211 unsigned CPI;
212 unsigned RefCount;
213 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
214 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
215 };
216
217 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000218 /// instructions. For each original constpool index (i.e. those that
219 /// existed upon entry to this pass), it keeps a vector of entries.
220 /// Original elements are cloned as we go along; the clones are
221 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000222 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000223
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000224 /// ImmBranch - One per immediate branch, keeping the machine instruction
225 /// pointer, conditional or unconditional, the max displacement,
226 /// and (if isCond is true) the corresponding unconditional branch
227 /// opcode.
228 struct ImmBranch {
229 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000230 unsigned MaxDisp : 31;
231 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000232 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000233 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
234 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000235 };
236
Evan Cheng2706f972007-05-16 05:14:06 +0000237 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000239 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000240
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000241 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
242 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000243 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000244
Evan Cheng5657c012009-07-29 02:18:14 +0000245 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
246 SmallVector<MachineInstr*, 4> T2JumpTables;
247
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000248 /// HasFarJump - True if any far jump instruction has been emitted during
249 /// the branch fix up pass.
250 bool HasFarJump;
251
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000252 MachineFunction *MF;
253 MachineConstantPool *MCP;
Chris Lattner20628752010-07-22 21:27:00 +0000254 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000255 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000256 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000257 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000258 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000259 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000260 public:
Devang Patel19974732007-05-03 01:11:54 +0000261 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000262 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000263
Evan Cheng5657c012009-07-29 02:18:14 +0000264 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000265
266 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000267 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000268 }
Bob Wilson84945262009-05-12 17:09:30 +0000269
Evan Chenga8e29892007-01-19 07:51:42 +0000270 private:
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000271 void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000272 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000273 void JumpTableFunctionScan();
274 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000275 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000276 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000277 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000278 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000279 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000280 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000281 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000282 MachineBasicBlock *&NewMBB);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000283 bool HandleConstantPoolUser(unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000284 void RemoveDeadCPEMI(MachineInstr *CPEMI);
285 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000286 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000287 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
288 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000289 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000290 CPUser &U);
Evan Chengc0dbec72007-01-31 19:57:44 +0000291 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000292 bool FixUpImmediateBr(ImmBranch &Br);
293 bool FixUpConditionalBr(ImmBranch &Br);
294 bool FixUpUnconditionalBr(ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000295 bool UndoLRSpillRestore();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000296 bool OptimizeThumb2Instructions();
297 bool OptimizeThumb2Branches();
298 bool ReorderThumb2JumpTables();
299 bool OptimizeThumb2JumpTables();
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000300 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
301 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000302
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000303 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000304 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000305 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000306 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000307
308 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
309 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
310 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
311 const CPUser &U) {
312 return OffsetIsInRange(UserOffset, TrialOffset,
313 U.MaxDisp, U.NegOk, U.IsSoImm);
314 }
Evan Chenga8e29892007-01-19 07:51:42 +0000315 };
Devang Patel19974732007-05-03 01:11:54 +0000316 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000317}
318
Dale Johannesen8593e412007-04-29 19:19:30 +0000319/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000320void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000321#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000322 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000323 MBBI != E; ++MBBI) {
324 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000325 unsigned Align = MBB->getAlignment();
326 unsigned MBBId = MBB->getNumber();
327 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
328 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000329 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000330 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
331 CPUser &U = CPUsers[i];
332 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000333 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
334 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
335 UserOffset - CPEOffset;
336 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000337 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000338#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000339}
340
341/// print block size and offset information - debugging
342void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000343 DEBUG({
344 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
345 const BasicBlockInfo &BBI = BBInfo[J];
346 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
347 << " kb=" << unsigned(BBI.KnownBits)
348 << " ua=" << unsigned(BBI.Unalign)
349 << " pa=" << unsigned(BBI.PostAlign)
350 << format(" size=%#x\n", BBInfo[J].Size);
351 }
352 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000353}
354
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000355/// createARMConstantIslandPass - returns an instance of the constpool
356/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000357FunctionPass *llvm::createARMConstantIslandPass() {
358 return new ARMConstantIslands();
359}
360
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000361bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
362 MF = &mf;
363 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000364
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000365 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000366 << MCP->getConstants().size() << " CP entries, aligned to "
367 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000368
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000369 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
370 AFI = MF->getInfo<ARMFunctionInfo>();
371 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000372
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000373 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000374 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000375 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000376
377 HasFarJump = false;
378
Evan Chenga8e29892007-01-19 07:51:42 +0000379 // Renumber all of the machine basic blocks in the function, guaranteeing that
380 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000381 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000382
Jim Grosbach80697d12009-11-12 17:25:07 +0000383 // Try to reorder and otherwise adjust the block layout to make good use
384 // of the TB[BH] instructions.
385 bool MadeChange = false;
386 if (isThumb2 && AdjustJumpTableBlocks) {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000387 JumpTableFunctionScan();
388 MadeChange |= ReorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000389 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000390 T2JumpTables.clear();
391 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000392 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000393 }
394
Evan Chengd26b14c2009-07-31 18:28:05 +0000395 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000396 // This is so we can keep exact track of where the alignment padding goes.
397
Chris Lattner7d7dab02010-01-27 23:37:36 +0000398 // ARM and Thumb2 functions need to be 4-byte aligned.
399 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000400 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000401
Evan Chenga8e29892007-01-19 07:51:42 +0000402 // Perform the initial placement of the constant pool entries. To start with,
403 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000404 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000405 if (!MCP->isEmpty()) {
406 DoInitialPlacement(CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000407 if (isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000408 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000409 }
Bob Wilson84945262009-05-12 17:09:30 +0000410
Evan Chenga8e29892007-01-19 07:51:42 +0000411 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000412 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000413
Evan Chenga8e29892007-01-19 07:51:42 +0000414 // Do the initial scan of the function, building up information about the
415 // sizes of each block, the location of all the water, and finding all of the
416 // constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000417 InitialFunctionScan(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000418 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000419 DEBUG(dumpBBs());
420
Bob Wilson84945262009-05-12 17:09:30 +0000421
Evan Chenged884f32007-04-03 23:39:48 +0000422 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000423 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000424
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000425 // Iteratively place constant pool entries and fix up branches until there
426 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000427 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000428 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000429 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000430 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000431 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000432 CPChange |= HandleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000433 if (CPChange && ++NoCPIters > 30)
434 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000435 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000436
Bob Wilsonb9239532009-10-15 20:49:47 +0000437 // Clear NewWaterList now. If we split a block for branches, it should
438 // appear as "new water" for the next iteration of constant pool placement.
439 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000440
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000441 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000442 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000443 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000444 BRChange |= FixUpImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000445 if (BRChange && ++NoBRIters > 30)
446 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000447 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000448
449 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000450 break;
451 MadeChange = true;
452 }
Evan Chenged884f32007-04-03 23:39:48 +0000453
Evan Chenga1efbbd2009-08-14 00:32:16 +0000454 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000455 if (isThumb2 && !STI->prefers32BitThumb())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000456 MadeChange |= OptimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000457
Dale Johannesen8593e412007-04-29 19:19:30 +0000458 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000459 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000460
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000461 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
462 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000463 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000464 MadeChange |= UndoLRSpillRestore();
465
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000466 // Save the mapping between original and cloned constpool entries.
467 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
468 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
469 const CPEntry & CPE = CPEntries[i][j];
470 AFI->recordCPEClone(i, CPE.CPI);
471 }
472 }
473
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000474 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000475
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000476 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000477 WaterList.clear();
478 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000479 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000480 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000481 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000482 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000483
484 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000485}
486
487/// DoInitialPlacement - Perform the initial placement of the constant pool
488/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000489void
490ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000491 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000492 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
493 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000494
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000495 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000496 unsigned MaxAlign = Log2_32(MF->getConstantPool()->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000497
498 // Mark the basic block as required by the const-pool.
499 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
500 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
501
502 // Order the entries in BB by descending alignment. That ensures correct
503 // alignment of all entries as long as BB is sufficiently aligned. Keep
504 // track of the insertion point for each alignment. We are going to bucket
505 // sort the entries as they are created.
506 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000507
Evan Chenga8e29892007-01-19 07:51:42 +0000508 // Add all of the constants from the constant pool to the end block, use an
509 // identity mapping of CPI's to CPE's.
510 const std::vector<MachineConstantPoolEntry> &CPs =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000511 MF->getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000512
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000513 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000514 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000515 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000516 assert(Size >= 4 && "Too small constant pool entry");
517 unsigned Align = CPs[i].getAlignment();
518 assert(isPowerOf2_32(Align) && "Invalid alignment");
519 // Verify that all constant pool entries are a multiple of their alignment.
520 // If not, we would have to pad them out so that instructions stay aligned.
521 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
522
523 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
524 unsigned LogAlign = Log2_32(Align);
525 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000526 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000527 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000528 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000529 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000530
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000531 // Ensure that future entries with higher alignment get inserted before
532 // CPEMI. This is bucket sort with iterators.
533 for (unsigned a = LogAlign + 1; a < MaxAlign; ++a)
534 if (InsPoint[a] == InsAt)
535 InsPoint[a] = CPEMI;
536
Evan Chengc99ef082007-02-09 20:54:44 +0000537 // Add a new CPEntry, but no corresponding CPUser yet.
538 std::vector<CPEntry> CPEs;
539 CPEs.push_back(CPEntry(CPEMI, i));
540 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000541 ++NumCPEs;
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000542 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000543 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000544 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000545}
546
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000547/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000548/// into the block immediately after it.
549static bool BBHasFallthrough(MachineBasicBlock *MBB) {
550 // Get the next machine basic block in the function.
551 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000552 // Can't fall off end of function.
553 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000554 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000555
Chris Lattner7896c9f2009-12-03 00:50:42 +0000556 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000557 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
558 E = MBB->succ_end(); I != E; ++I)
559 if (*I == NextBB)
560 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000561
Evan Chenga8e29892007-01-19 07:51:42 +0000562 return false;
563}
564
Evan Chengc99ef082007-02-09 20:54:44 +0000565/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
566/// look up the corresponding CPEntry.
567ARMConstantIslands::CPEntry
568*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
569 const MachineInstr *CPEMI) {
570 std::vector<CPEntry> &CPEs = CPEntries[CPI];
571 // Number of entries per constpool index should be small, just do a
572 // linear search.
573 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
574 if (CPEs[i].CPEMI == CPEMI)
575 return &CPEs[i];
576 }
577 return NULL;
578}
579
Jim Grosbach80697d12009-11-12 17:25:07 +0000580/// JumpTableFunctionScan - Do a scan of the function, building up
581/// information about the sizes of each block and the locations of all
582/// the jump tables.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000583void ARMConstantIslands::JumpTableFunctionScan() {
584 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000585 MBBI != E; ++MBBI) {
586 MachineBasicBlock &MBB = *MBBI;
587
Jim Grosbach80697d12009-11-12 17:25:07 +0000588 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000589 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000590 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000591 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000592 }
593}
594
Evan Chenga8e29892007-01-19 07:51:42 +0000595/// InitialFunctionScan - Do the initial scan of the function, building up
596/// information about the sizes of each block, the location of all the water,
597/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000598void ARMConstantIslands::
599InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000600 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000601 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000602
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000603 // First thing, compute the size of all basic blocks, and see if the function
604 // has any inline assembly in it. If so, we have to be conservative about
605 // alignment assumptions, as we don't know for sure the size of any
606 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000607 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000608 ComputeBlockSize(I);
609
610 // The known bits of the entry block offset are determined by the function
611 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000612 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000613
614 // Compute block offsets and known bits.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000615 AdjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000616
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000617 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000618 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000619 MBBI != E; ++MBBI) {
620 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000621
Evan Chenga8e29892007-01-19 07:51:42 +0000622 // If this block doesn't fall through into the next MBB, then this is
623 // 'water' that a constant pool island could be placed.
624 if (!BBHasFallthrough(&MBB))
625 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000626
Evan Chenga8e29892007-01-19 07:51:42 +0000627 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
628 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000629 if (I->isDebugValue())
630 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000631
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000632 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000633 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000634 bool isCond = false;
635 unsigned Bits = 0;
636 unsigned Scale = 1;
637 int UOpc = Opc;
638 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000639 default:
640 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000641 case ARM::t2BR_JT:
642 T2JumpTables.push_back(I);
643 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000644 case ARM::Bcc:
645 isCond = true;
646 UOpc = ARM::B;
647 // Fallthrough
648 case ARM::B:
649 Bits = 24;
650 Scale = 4;
651 break;
652 case ARM::tBcc:
653 isCond = true;
654 UOpc = ARM::tB;
655 Bits = 8;
656 Scale = 2;
657 break;
658 case ARM::tB:
659 Bits = 11;
660 Scale = 2;
661 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000662 case ARM::t2Bcc:
663 isCond = true;
664 UOpc = ARM::t2B;
665 Bits = 20;
666 Scale = 2;
667 break;
668 case ARM::t2B:
669 Bits = 24;
670 Scale = 2;
671 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000672 }
Evan Chengb43216e2007-02-01 10:16:15 +0000673
674 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000675 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000676 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000677 }
678
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000679 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
680 PushPopMIs.push_back(I);
681
Evan Chengd3d9d662009-07-23 18:27:47 +0000682 if (Opc == ARM::CONSTPOOL_ENTRY)
683 continue;
684
Evan Chenga8e29892007-01-19 07:51:42 +0000685 // Scan the instructions for constant pool operands.
686 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000687 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000688 // We found one. The addressing mode tells us the max displacement
689 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000690
Evan Chenga8e29892007-01-19 07:51:42 +0000691 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000692 unsigned Bits = 0;
693 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000694 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000695 bool IsSoImm = false;
696
697 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000698 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000699 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000700 break;
701
702 // Taking the address of a CP entry.
703 case ARM::LEApcrel:
704 // This takes a SoImm, which is 8 bit immediate rotated. We'll
705 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000706 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000707 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000708 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000709 Scale = 4;
710 NegOk = true;
711 IsSoImm = true;
712 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000713 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000714 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000715 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000716 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000717 case ARM::tLEApcrel:
718 Bits = 8;
719 Scale = 4;
720 break;
721
Jim Grosbach3e556122010-10-26 22:37:02 +0000722 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000723 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000724 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000725 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000726 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000727 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000728
729 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000730 Bits = 8;
731 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000732 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000733
Jim Grosbache5165492009-11-09 00:11:35 +0000734 case ARM::VLDRD:
735 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000736 Bits = 8;
737 Scale = 4; // +-(offset_8*4)
738 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000739 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000740 }
Evan Chengb43216e2007-02-01 10:16:15 +0000741
Evan Chenga8e29892007-01-19 07:51:42 +0000742 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000743 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000744 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000745 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000746 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000747
748 // Increment corresponding CPEntry reference count.
749 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
750 assert(CPE && "Cannot find a corresponding CPEntry!");
751 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000752
Evan Chenga8e29892007-01-19 07:51:42 +0000753 // Instructions can only use one CP entry, don't bother scanning the
754 // rest of the operands.
755 break;
756 }
757 }
Evan Chenga8e29892007-01-19 07:51:42 +0000758 }
759}
760
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000761/// ComputeBlockSize - Compute the size and some alignment information for MBB.
762/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000763void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000764 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
765 BBI.Size = 0;
766 BBI.Unalign = 0;
767 BBI.PostAlign = 0;
768
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000769 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
770 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000771 BBI.Size += TII->GetInstSizeInBytes(I);
772 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
773 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000774 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000775 BBI.Unalign = isThumb ? 1 : 2;
776 }
777
778 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000779 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000780 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000781 MBB->getParent()->EnsureAlignment(2);
782 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000783}
784
Evan Chenga8e29892007-01-19 07:51:42 +0000785/// GetOffsetOf - Return the current offset of the specified machine instruction
786/// from the start of the function. This offset changes as stuff is moved
787/// around inside the function.
788unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
789 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000790
Evan Chenga8e29892007-01-19 07:51:42 +0000791 // The offset is composed of two things: the sum of the sizes of all MBB's
792 // before this instruction's block, and the offset from the start of the block
793 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000794 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000795
796 // Sum instructions before MI in MBB.
797 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
798 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
799 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000800 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000801 }
802}
803
804/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
805/// ID.
806static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
807 const MachineBasicBlock *RHS) {
808 return LHS->getNumber() < RHS->getNumber();
809}
810
811/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
812/// machine function, it upsets all of the block numbers. Renumber the blocks
813/// and update the arrays that parallel this numbering.
814void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000815 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000816 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000817
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000818 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000819 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000820 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000821
822 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000823 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000824 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000825 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
826 CompareMBBNumbers);
827 WaterList.insert(IP, NewBB);
828}
829
830
831/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000832/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000833/// account for this change and returns the newly created block.
834MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000835 MachineBasicBlock *OrigBB = MI->getParent();
836
837 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000838 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000839 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000840 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000841 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000842
Evan Chenga8e29892007-01-19 07:51:42 +0000843 // Splice the instructions starting with MI over to NewBB.
844 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000845
Evan Chenga8e29892007-01-19 07:51:42 +0000846 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000847 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000848 // There doesn't seem to be meaningful DebugInfo available; this doesn't
849 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000850 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000851 if (!isThumb)
852 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
853 else
854 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
855 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000856 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000857
Evan Chenga8e29892007-01-19 07:51:42 +0000858 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000859 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000860
Evan Chenga8e29892007-01-19 07:51:42 +0000861 // OrigBB branches to NewBB.
862 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000863
Evan Chenga8e29892007-01-19 07:51:42 +0000864 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000865 // This is almost the same as UpdateForInsertedWaterBlock, except that
866 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000867 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000868
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000869 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000870 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000871 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000872
Bob Wilson84945262009-05-12 17:09:30 +0000873 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000874 // available water after it (but not if it's already there, which happens
875 // when splitting before a conditional branch that is followed by an
876 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000877 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000878 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
879 CompareMBBNumbers);
880 MachineBasicBlock* WaterBB = *IP;
881 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000882 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883 else
884 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000885 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886
Dale Johannesen8086d582010-07-23 22:50:23 +0000887 // Figure out how large the OrigBB is. As the first half of the original
888 // block, it cannot contain a tablejump. The size includes
889 // the new jump we added. (It should be possible to do this without
890 // recounting everything, but it's very confusing, and this is rarely
891 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000892 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000893
Dale Johannesen8086d582010-07-23 22:50:23 +0000894 // Figure out how large the NewMBB is. As the second half of the original
895 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000896 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000897
Dale Johannesen99c49a42007-02-25 00:47:03 +0000898 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000899 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000900
901 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000902}
903
Dale Johannesen8593e412007-04-29 19:19:30 +0000904/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000905/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000906/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000907bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000908 unsigned TrialOffset, unsigned MaxDisp,
909 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000910 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
911 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000912 // Effectively, the valid range of displacements is 2 bytes smaller for such
913 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000914 unsigned TotalAdj = 0;
915 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000916 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000917 TotalAdj = 2;
918 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000919 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000920 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000921 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000922 TotalAdj += 2;
923 }
924
925 // In Thumb2 mode, later branch adjustments can shift instructions up and
926 // cause alignment change. In the worst case scenario this can cause the
927 // user's effective address to be subtracted by 2 and the CPE's address to
928 // be plus 2.
929 if (isThumb2 && TotalAdj != 4)
930 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000931
Dale Johannesen99c49a42007-02-25 00:47:03 +0000932 if (UserOffset <= TrialOffset) {
933 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000934 if (TrialOffset - UserOffset <= MaxDisp)
935 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000936 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000937 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000938 if (UserOffset - TrialOffset <= MaxDisp)
939 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000940 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000941 }
942 return false;
943}
944
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000945/// WaterIsInRange - Returns true if a CPE placed after the specified
946/// Water (a basic block) will be in range for the specific MI.
947
948bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000949 MachineBasicBlock* Water, CPUser &U) {
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000950 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000951
Dale Johannesend959aa42007-04-02 20:31:06 +0000952 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000953 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000954 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000955 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000956
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000957 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000958}
959
960/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000961/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000962bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000963 MachineInstr *CPEMI, unsigned MaxDisp,
964 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000965 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000966 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000967
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000968 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000969 DEBUG({
970 unsigned Block = MI->getParent()->getNumber();
971 const BasicBlockInfo &BBI = BBInfo[Block];
972 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
973 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000974 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000975 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000976 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
977 << format("CPE address=%#x offset=%+d: ", CPEOffset,
978 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000979 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000980 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000981
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000982 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000983}
984
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000985#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000986/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
987/// unconditionally branches to its only successor.
988static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
989 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
990 return false;
991
992 MachineBasicBlock *Succ = *MBB->succ_begin();
993 MachineBasicBlock *Pred = *MBB->pred_begin();
994 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000995 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
996 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000997 return PredMI->getOperand(0).getMBB() == Succ;
998 return false;
999}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001000#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001001
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001002void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001003 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1004 // Get the offset and known bits at the end of the layout predecessor.
1005 unsigned Offset = BBInfo[i - 1].postOffset();
1006 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
1007
1008 // Add padding before an aligned block. This may teach us more bits.
1009 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
1010 Offset = WorstCaseAlign(Offset, Align, KnownBits);
1011 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +00001012 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001013
1014 // This is where block i begins.
1015 BBInfo[i].Offset = Offset;
1016 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001017 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001018}
1019
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001020/// DecrementOldEntry - find the constant pool entry with index CPI
1021/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001022/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001023/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001024
Evan Chenged884f32007-04-03 23:39:48 +00001025bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001026 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001027 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1028 assert(CPE && "Unexpected!");
1029 if (--CPE->RefCount == 0) {
1030 RemoveDeadCPEMI(CPEMI);
1031 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001032 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001033 return true;
1034 }
1035 return false;
1036}
1037
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001038/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1039/// if not, see if an in-range clone of the CPE is in range, and if so,
1040/// change the data structures so the user references the clone. Returns:
1041/// 0 = no existing entry found
1042/// 1 = entry found, and there were no code insertions or deletions
1043/// 2 = entry found, and there were code insertions or deletions
1044int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1045{
1046 MachineInstr *UserMI = U.MI;
1047 MachineInstr *CPEMI = U.CPEMI;
1048
1049 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001050 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001051 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001052 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001053 }
1054
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001055 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001056 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001057 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1058 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1059 // We already tried this one
1060 if (CPEs[i].CPEMI == CPEMI)
1061 continue;
1062 // Removing CPEs can leave empty entries, skip
1063 if (CPEs[i].CPEMI == NULL)
1064 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001065 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001066 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001067 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001068 // Point the CPUser node to the replacement
1069 U.CPEMI = CPEs[i].CPEMI;
1070 // Change the CPI in the instruction operand to refer to the clone.
1071 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001072 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001073 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001074 break;
1075 }
1076 // Adjust the refcount of the clone...
1077 CPEs[i].RefCount++;
1078 // ...and the original. If we didn't remove the old entry, none of the
1079 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001080 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001081 }
1082 }
1083 return 0;
1084}
1085
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001086/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1087/// the specific unconditional branch instruction.
1088static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001089 switch (Opc) {
1090 case ARM::tB:
1091 return ((1<<10)-1)*2;
1092 case ARM::t2B:
1093 return ((1<<23)-1)*2;
1094 default:
1095 break;
1096 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001097
David Goodwin5e47a9a2009-06-30 18:04:13 +00001098 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001099}
1100
Bob Wilsonb9239532009-10-15 20:49:47 +00001101/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001102/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001103/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001104/// is set to the WaterList entry. For Thumb, prefer water that will not
1105/// introduce padding to water that will. To ensure that this pass
1106/// terminates, the CPE location for a particular CPUser is only allowed to
1107/// move to a lower address, so search backward from the end of the list and
1108/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001109bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001110 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001111 if (WaterList.empty())
1112 return false;
1113
Bob Wilson32c50e82009-10-12 20:45:53 +00001114 bool FoundWaterThatWouldPad = false;
1115 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001116 for (water_iterator IP = prior(WaterList.end()),
1117 B = WaterList.begin();; --IP) {
1118 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001119 // Check if water is in range and is either at a lower address than the
1120 // current "high water mark" or a new water block that was created since
1121 // the previous iteration by inserting an unconditional branch. In the
1122 // latter case, we want to allow resetting the high water mark back to
1123 // this new water since we haven't seen it before. Inserting branches
1124 // should be relatively uncommon and when it does happen, we want to be
1125 // sure to take advantage of it for all the CPEs near that block, so that
1126 // we don't insert more branches than necessary.
1127 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1128 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1129 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001130 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001131 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001132 // This is valid Water, but would introduce padding. Remember
1133 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001134 if (!FoundWaterThatWouldPad) {
1135 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001136 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001137 }
Bob Wilson3b757352009-10-12 19:04:03 +00001138 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001139 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001140 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001141 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001142 }
Bob Wilson3b757352009-10-12 19:04:03 +00001143 if (IP == B)
1144 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001145 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001146 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001147 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001148 return true;
1149 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001150 return false;
1151}
1152
Bob Wilson84945262009-05-12 17:09:30 +00001153/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001154/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1155/// block is used if in range, and the conditional branch munged so control
1156/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001157/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001158/// block following which the new island can be inserted (the WaterList
1159/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001160void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001161 unsigned UserOffset,
1162 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001163 CPUser &U = CPUsers[CPUserIndex];
1164 MachineInstr *UserMI = U.MI;
1165 MachineInstr *CPEMI = U.CPEMI;
1166 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001167 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1168 unsigned OffsetOfNextBlock = UserBBI.postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001169
Bob Wilson36fa5322009-10-15 05:10:36 +00001170 // If the block does not end in an unconditional branch already, and if the
1171 // end of the block is within range, make new water there. (The addition
1172 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1173 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001174 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001175 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001176 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001177 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001178 if (&UserMBB->back() == UserMI)
1179 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001180 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001181 // Add an unconditional branch from UserMBB to fallthrough block.
1182 // Record it for branch lengthening; this new branch will not get out of
1183 // range, but if the preceding conditional branch is out of range, the
1184 // targets will be exchanged, and the altered branch may be out of
1185 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001186 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001187 if (!isThumb)
1188 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1189 else
1190 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1191 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001192 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001193 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001194 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001195 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001196 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001197 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001198 } else {
1199 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001200 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001201 // and constant pool entries are 4 bytes: if instruction I references
1202 // island CPE, and instruction I+1 references CPE', it will
1203 // not work well to put CPE as far forward as possible, since then
1204 // CPE' cannot immediately follow it (that location is 2 bytes
1205 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001206 // a new island. So, we make a first guess, then walk through the
1207 // instructions between the one currently being looked at and the
1208 // possible insertion point, and make sure any other instructions
1209 // that reference CPEs will be able to use the same island area;
1210 // if not, we back up the insertion point.
1211
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001212 // Try to split the block so it's fully aligned. Compute the latest split
1213 // point where we can add a 4-byte branch instruction, and then
1214 // WorstCaseAlign to LogAlign.
1215 unsigned LogAlign = UserMBB->getParent()->getAlignment();
1216 unsigned KnownBits = UserBBI.internalKnownBits();
1217 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1218 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1219 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1220 BaseInsertOffset));
1221
1222 // Account for alignment and unknown padding.
1223 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1224 BaseInsertOffset -= UPad;
1225
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001226 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001227 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001228 // island is handled inside OffsetIsInRange.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001229 BaseInsertOffset -= 4;
1230
1231 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1232 << " la=" << LogAlign
1233 << " kb=" << KnownBits
1234 << " up=" << UPad << '\n');
1235
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001236 // This could point off the end of the block if we've already got
1237 // constant pool entries following this block; only the last one is
1238 // in the water list. Back past any possible branches (allow for a
1239 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001240 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1241 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001242 (isThumb1 ? 6 : 8);
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001243 unsigned EndInsertOffset =
1244 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1245 CPEMI->getOperand(2).getImm();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001246 MachineBasicBlock::iterator MI = UserMI;
1247 ++MI;
1248 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001249 unsigned NumCPUsers = CPUsers.size();
1250 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001251 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001252 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001253 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001254 MI = llvm::next(MI)) {
1255 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001256 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001257 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001258 BaseInsertOffset -= 1u << LogAlign;
1259 EndInsertOffset -= 1u << LogAlign;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001260 }
1261 // This is overly conservative, as we don't account for CPEMIs
1262 // being reused within the block, but it doesn't matter much.
1263 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1264 CPUIndex++;
1265 }
Evan Cheng719510a2010-08-12 20:30:05 +00001266
1267 // Remember the last IT instruction.
1268 if (MI->getOpcode() == ARM::t2IT)
1269 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001270 }
Evan Cheng719510a2010-08-12 20:30:05 +00001271
Evan Cheng719510a2010-08-12 20:30:05 +00001272 --MI;
1273
1274 // Avoid splitting an IT block.
1275 if (LastIT) {
1276 unsigned PredReg = 0;
1277 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1278 if (CC != ARMCC::AL)
1279 MI = LastIT;
1280 }
1281 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001282 }
1283}
1284
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001285/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001286/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001287/// place in-range. Return true if we changed any addresses (thus must run
1288/// another pass of branch lengthening), false otherwise.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001289bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001290 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001291 MachineInstr *UserMI = U.MI;
1292 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001293 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001294 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001295 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001296 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001297 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001298
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001299 // See if the current entry is within range, or there is a clone of it
1300 // in range.
1301 int result = LookForExistingCPEntry(U, UserOffset);
1302 if (result==1) return false;
1303 else if (result==2) return true;
1304
1305 // No existing clone of this CPE is within range.
1306 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001307 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001308
Bob Wilsonf98032e2009-10-12 21:23:15 +00001309 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001310 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001311 MachineBasicBlock *NewMBB;
1312 water_iterator IP;
1313 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001314 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001315 MachineBasicBlock *WaterBB = *IP;
1316
1317 // If the original WaterList entry was "new water" on this iteration,
1318 // propagate that to the new island. This is just keeping NewWaterList
1319 // updated to match the WaterList, which will be updated below.
1320 if (NewWaterList.count(WaterBB)) {
1321 NewWaterList.erase(WaterBB);
1322 NewWaterList.insert(NewIsland);
1323 }
1324 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001325 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001326
1327 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001328 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001329 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001330 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001331
1332 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1333 // called while handling branches so that the water will be seen on the
1334 // next iteration for constant pools, but in this context, we don't want
1335 // it. Check for this so it will be removed from the WaterList.
1336 // Also remove any entry from NewWaterList.
1337 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1338 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1339 if (IP != WaterList.end())
1340 NewWaterList.erase(WaterBB);
1341
1342 // We are adding new water. Update NewWaterList.
1343 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001344 }
1345
Bob Wilsonb9239532009-10-15 20:49:47 +00001346 // Remove the original WaterList entry; we want subsequent insertions in
1347 // this vicinity to go after the one we're about to insert. This
1348 // considerably reduces the number of times we have to move the same CPE
1349 // more than once and is also important to ensure the algorithm terminates.
1350 if (IP != WaterList.end())
1351 WaterList.erase(IP);
1352
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001353 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001354 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001355
1356 // Update internal data structures to account for the newly inserted MBB.
1357 UpdateForInsertedWaterBlock(NewIsland);
1358
1359 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001360 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001361
1362 // Now that we have an island to add the CPE to, clone the original CPE and
1363 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001364 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001365 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001366 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001367 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001368 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001369
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001370 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1371 NewIsland->setAlignment(2);
1372
Evan Chenga8e29892007-01-19 07:51:42 +00001373 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001374 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001375 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001376
Evan Chenga8e29892007-01-19 07:51:42 +00001377 // Finally, change the CPI in the instruction operand to be ID.
1378 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001379 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001380 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001381 break;
1382 }
Bob Wilson84945262009-05-12 17:09:30 +00001383
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001384 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001385 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001386
Evan Chenga8e29892007-01-19 07:51:42 +00001387 return true;
1388}
1389
Evan Chenged884f32007-04-03 23:39:48 +00001390/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1391/// sizes and offsets of impacted basic blocks.
1392void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1393 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001394 unsigned Size = CPEMI->getOperand(2).getImm();
1395 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001396 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001397 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001398 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001399 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001400 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001401 // empty, so fix this.
1402 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001403 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1404 Size += BBInfo[CPEBB->getNumber()].Size;
1405 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001406 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001407
1408 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1409 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001410 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001411 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001412 // An island has only one predecessor BB and one successor BB. Check if
1413 // this BB's predecessor jumps directly to this BB's successor. This
1414 // shouldn't happen currently.
1415 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1416 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001417}
1418
1419/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1420/// are zero.
1421bool ARMConstantIslands::RemoveUnusedCPEntries() {
1422 unsigned MadeChange = false;
1423 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1424 std::vector<CPEntry> &CPEs = CPEntries[i];
1425 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1426 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1427 RemoveDeadCPEMI(CPEs[j].CPEMI);
1428 CPEs[j].CPEMI = NULL;
1429 MadeChange = true;
1430 }
1431 }
Bob Wilson84945262009-05-12 17:09:30 +00001432 }
Evan Chenged884f32007-04-03 23:39:48 +00001433 return MadeChange;
1434}
1435
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001436/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001437/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001438bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1439 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001440 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001441 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001442 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001443
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001444 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001445 << " from BB#" << MI->getParent()->getNumber()
1446 << " max delta=" << MaxDisp
1447 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1448 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001449
Dale Johannesen8593e412007-04-29 19:19:30 +00001450 if (BrOffset <= DestOffset) {
1451 // Branch before the Dest.
1452 if (DestOffset-BrOffset <= MaxDisp)
1453 return true;
1454 } else {
1455 if (BrOffset-DestOffset <= MaxDisp)
1456 return true;
1457 }
1458 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001459}
1460
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001461/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1462/// away to fit in its displacement field.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001463bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001464 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001465 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001466
Evan Chengc0dbec72007-01-31 19:57:44 +00001467 // Check to see if the DestBB is already in-range.
1468 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001469 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001470
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001471 if (!Br.isCond)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001472 return FixUpUnconditionalBr(Br);
1473 return FixUpConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001474}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001475
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001476/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1477/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001478/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001479/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001480bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001481ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001482 MachineInstr *MI = Br.MI;
1483 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001484 if (!isThumb1)
1485 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001486
1487 // Use BL to implement far jump.
1488 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001489 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001490 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001491 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001492 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001493 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001494
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001495 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001496
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001497 return true;
1498}
1499
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001500/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001501/// far away to fit in its displacement field. It is converted to an inverse
1502/// conditional branch + an unconditional branch to the destination.
1503bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001504ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001505 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001506 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001507
Bob Wilson39bf0512009-05-12 17:35:29 +00001508 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001509 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001510 // blt L1
1511 // =>
1512 // bge L2
1513 // b L1
1514 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001515 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001516 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001517 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001518
1519 // If the branch is at the end of its MBB and that has a fall-through block,
1520 // direct the updated conditional branch to the fall-through block. Otherwise,
1521 // split the MBB before the next instruction.
1522 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001523 MachineInstr *BMI = &MBB->back();
1524 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001525
Dan Gohmanfe601042010-06-22 15:08:57 +00001526 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001527 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001528 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001529 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001530 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001531 // condition and swap destinations:
1532 // beq L1
1533 // b L2
1534 // =>
1535 // bne L2
1536 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001537 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001538 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001539 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001540 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001541 BMI->getOperand(0).setMBB(DestBB);
1542 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001543 MI->getOperand(1).setImm(CC);
1544 return true;
1545 }
1546 }
1547 }
1548
1549 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001550 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001551 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001552 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001553 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001554 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001555 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001556 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001557 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001558 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001559
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001560 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001561 << " also invert condition and change dest. to BB#"
1562 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001563
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001564 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001565 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001566 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001567 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001568 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001569 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001570 if (isThumb)
1571 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1572 .addImm(ARMCC::AL).addReg(0);
1573 else
1574 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001575 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001576 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001577 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001578
1579 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001580 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001581 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001582 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001583 return true;
1584}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001585
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001586/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001587/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1588/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001589bool ARMConstantIslands::UndoLRSpillRestore() {
1590 bool MadeChange = false;
1591 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1592 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001593 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001594 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001595 MI->getOperand(2).getReg() == ARM::PC &&
1596 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001597 // Create the new insn and copy the predicate from the old.
1598 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1599 .addOperand(MI->getOperand(0))
1600 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001601 MI->eraseFromParent();
1602 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001603 }
1604 }
1605 return MadeChange;
1606}
Evan Cheng5657c012009-07-29 02:18:14 +00001607
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001608bool ARMConstantIslands::OptimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001609 bool MadeChange = false;
1610
1611 // Shrink ADR and LDR from constantpool.
1612 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1613 CPUser &U = CPUsers[i];
1614 unsigned Opcode = U.MI->getOpcode();
1615 unsigned NewOpc = 0;
1616 unsigned Scale = 1;
1617 unsigned Bits = 0;
1618 switch (Opcode) {
1619 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001620 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001621 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1622 NewOpc = ARM::tLEApcrel;
1623 Bits = 8;
1624 Scale = 4;
1625 }
1626 break;
1627 case ARM::t2LDRpci:
1628 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1629 NewOpc = ARM::tLDRpci;
1630 Bits = 8;
1631 Scale = 4;
1632 }
1633 break;
1634 }
1635
1636 if (!NewOpc)
1637 continue;
1638
1639 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1640 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1641 // FIXME: Check if offset is multiple of scale if scale is not 4.
1642 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1643 U.MI->setDesc(TII->get(NewOpc));
1644 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001645 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001646 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001647 ++NumT2CPShrunk;
1648 MadeChange = true;
1649 }
1650 }
1651
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001652 MadeChange |= OptimizeThumb2Branches();
1653 MadeChange |= OptimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001654 return MadeChange;
1655}
1656
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001657bool ARMConstantIslands::OptimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001658 bool MadeChange = false;
1659
1660 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1661 ImmBranch &Br = ImmBranches[i];
1662 unsigned Opcode = Br.MI->getOpcode();
1663 unsigned NewOpc = 0;
1664 unsigned Scale = 1;
1665 unsigned Bits = 0;
1666 switch (Opcode) {
1667 default: break;
1668 case ARM::t2B:
1669 NewOpc = ARM::tB;
1670 Bits = 11;
1671 Scale = 2;
1672 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001673 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001674 NewOpc = ARM::tBcc;
1675 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001676 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001677 break;
1678 }
Evan Chengde17fb62009-10-31 23:46:45 +00001679 }
1680 if (NewOpc) {
1681 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1682 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1683 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1684 Br.MI->setDesc(TII->get(NewOpc));
1685 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001686 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001687 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001688 ++NumT2BrShrunk;
1689 MadeChange = true;
1690 }
1691 }
1692
1693 Opcode = Br.MI->getOpcode();
1694 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001695 continue;
1696
Evan Chengde17fb62009-10-31 23:46:45 +00001697 NewOpc = 0;
1698 unsigned PredReg = 0;
1699 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1700 if (Pred == ARMCC::EQ)
1701 NewOpc = ARM::tCBZ;
1702 else if (Pred == ARMCC::NE)
1703 NewOpc = ARM::tCBNZ;
1704 if (!NewOpc)
1705 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001706 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001707 // Check if the distance is within 126. Subtract starting offset by 2
1708 // because the cmp will be eliminated.
1709 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001710 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001711 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001712 MachineBasicBlock::iterator CmpMI = Br.MI;
1713 if (CmpMI != Br.MI->getParent()->begin()) {
1714 --CmpMI;
1715 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1716 unsigned Reg = CmpMI->getOperand(0).getReg();
1717 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1718 if (Pred == ARMCC::AL &&
1719 CmpMI->getOperand(1).getImm() == 0 &&
1720 isARMLowRegister(Reg)) {
1721 MachineBasicBlock *MBB = Br.MI->getParent();
1722 MachineInstr *NewBR =
1723 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1724 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1725 CmpMI->eraseFromParent();
1726 Br.MI->eraseFromParent();
1727 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001728 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001729 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001730 ++NumCBZ;
1731 MadeChange = true;
1732 }
Evan Chengde17fb62009-10-31 23:46:45 +00001733 }
1734 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001735 }
1736 }
1737
1738 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001739}
1740
Evan Chenga1efbbd2009-08-14 00:32:16 +00001741/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1742/// jumptables when it's possible.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001743bool ARMConstantIslands::OptimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001744 bool MadeChange = false;
1745
1746 // FIXME: After the tables are shrunk, can we get rid some of the
1747 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001748 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001749 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001750
Evan Cheng5657c012009-07-29 02:18:14 +00001751 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1752 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1753 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001754 const MCInstrDesc &MCID = MI->getDesc();
1755 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001756 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001757 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1758 unsigned JTI = JTOP.getIndex();
1759 assert(JTI < JT.size());
1760
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001761 bool ByteOk = true;
1762 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001763 unsigned JTOffset = GetOffsetOf(MI) + 4;
1764 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001765 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1766 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001767 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001768 // Negative offset is not ok. FIXME: We should change BB layout to make
1769 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001770 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001771 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001772 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001773 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001774 HalfWordOk = false;
1775 if (!ByteOk && !HalfWordOk)
1776 break;
1777 }
1778
1779 if (ByteOk || HalfWordOk) {
1780 MachineBasicBlock *MBB = MI->getParent();
1781 unsigned BaseReg = MI->getOperand(0).getReg();
1782 bool BaseRegKill = MI->getOperand(0).isKill();
1783 if (!BaseRegKill)
1784 continue;
1785 unsigned IdxReg = MI->getOperand(1).getReg();
1786 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001787
1788 // Scan backwards to find the instruction that defines the base
1789 // register. Due to post-RA scheduling, we can't count on it
1790 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001791 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001792 MachineBasicBlock::iterator B = MBB->begin();
1793 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1794 --PrevI;
1795
1796 // If for some reason we didn't find it, we can't do anything, so
1797 // just skip this one.
1798 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001799 continue;
1800
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001801 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001802 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001803 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001804 // Make sure it only defines the base register and kills any uses
1805 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001806 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1807 const MachineOperand &MO = AddrMI->getOperand(k);
1808 if (!MO.isReg() || !MO.getReg())
1809 continue;
1810 if (MO.isDef() && MO.getReg() != BaseReg) {
1811 OptOk = false;
1812 break;
1813 }
1814 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1815 OptOk = false;
1816 break;
1817 }
1818 }
1819 if (!OptOk)
1820 continue;
1821
Owen Anderson6b8719f2010-12-13 22:51:08 +00001822 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001823 // that gave us the initial base register definition.
1824 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1825 ;
1826
Owen Anderson6b8719f2010-12-13 22:51:08 +00001827 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001828 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001829 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001830 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001831 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001832 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001833 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001834
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001835 if (!OptOk)
1836 continue;
1837
Jim Grosbachd092a872010-11-29 21:28:32 +00001838 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001839 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1840 .addReg(IdxReg, getKillRegState(IdxRegKill))
1841 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1842 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1843 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1844 // is 2-byte aligned. For now, asm printer will fix it up.
1845 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1846 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1847 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1848 OrigSize += TII->GetInstSizeInBytes(MI);
1849
1850 AddrMI->eraseFromParent();
1851 LeaMI->eraseFromParent();
1852 MI->eraseFromParent();
1853
1854 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001855 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001856 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001857
1858 ++NumTBs;
1859 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001860 }
1861 }
1862
1863 return MadeChange;
1864}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001865
Jim Grosbach9249efe2009-11-16 18:55:47 +00001866/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1867/// jump tables always branch forwards, since that's what tbb and tbh need.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001868bool ARMConstantIslands::ReorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001869 bool MadeChange = false;
1870
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001871 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001872 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001873
Jim Grosbach80697d12009-11-12 17:25:07 +00001874 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1875 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1876 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001877 const MCInstrDesc &MCID = MI->getDesc();
1878 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001879 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001880 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1881 unsigned JTI = JTOP.getIndex();
1882 assert(JTI < JT.size());
1883
1884 // We prefer if target blocks for the jump table come after the jump
1885 // instruction so we can use TB[BH]. Loop through the target blocks
1886 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001887 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001888 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1889 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1890 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001891 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001892
Jim Grosbach08cbda52009-11-16 18:58:52 +00001893 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001894 // The destination precedes the switch. Try to move the block forward
1895 // so we have a positive offset.
1896 MachineBasicBlock *NewBB =
1897 AdjustJTTargetBlockForward(MBB, MI->getParent());
1898 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001899 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001900 MadeChange = true;
1901 }
1902 }
1903 }
1904
1905 return MadeChange;
1906}
1907
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001908MachineBasicBlock *ARMConstantIslands::
1909AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1910{
Jim Grosbach03e2d442010-07-07 22:53:35 +00001911 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001912 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001913 // table that branches back to the actual target. This is a very simple
1914 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001915 MachineBasicBlock *TBB = 0, *FBB = 0;
1916 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001917 SmallVector<MachineOperand, 4> CondPrior;
1918 MachineFunction::iterator BBi = BB;
1919 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001920
Jim Grosbachca215e72009-11-16 17:10:56 +00001921 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001922 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001923
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001924 // If the block ends in an unconditional branch, move it. The prior block
1925 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001926 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001927 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001928 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001929 BB->moveAfter(JTBB);
1930 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001931 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001932 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001933 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001934 ++NumJTMoved;
1935 return NULL;
1936 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001937
1938 // Create a new MBB for the code after the jump BB.
1939 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001940 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001941 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001942 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001943
1944 // Add an unconditional branch from NewBB to BB.
1945 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1946 // correspond directly to anything in the source.
1947 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001948 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1949 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001950
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001951 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001952 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001953
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001954 // Update the CFG.
1955 NewBB->addSuccessor(BB);
1956 JTBB->removeSuccessor(BB);
1957 JTBB->addSuccessor(NewBB);
1958
Jim Grosbach80697d12009-11-12 17:25:07 +00001959 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001960 return NewBB;
1961}