blob: fb8a76d27e9df055d237153cb79bb17756969c91 [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 Olesencca33a32011-12-12 18:45:45 +0000273 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000274 void JumpTableFunctionScan();
275 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000276 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000277 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000278 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000279 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000280 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000281 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000282 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000283 MachineBasicBlock *&NewMBB);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000284 bool HandleConstantPoolUser(unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000285 void RemoveDeadCPEMI(MachineInstr *CPEMI);
286 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000287 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000288 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
289 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000290 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000291 CPUser &U);
Evan Chengc0dbec72007-01-31 19:57:44 +0000292 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000293 bool FixUpImmediateBr(ImmBranch &Br);
294 bool FixUpConditionalBr(ImmBranch &Br);
295 bool FixUpUnconditionalBr(ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000296 bool UndoLRSpillRestore();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000297 bool OptimizeThumb2Instructions();
298 bool OptimizeThumb2Branches();
299 bool ReorderThumb2JumpTables();
300 bool OptimizeThumb2JumpTables();
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000301 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
302 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000303
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000304 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000305 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000306 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000307 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000308
309 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
310 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
311 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
312 const CPUser &U) {
313 return OffsetIsInRange(UserOffset, TrialOffset,
314 U.MaxDisp, U.NegOk, U.IsSoImm);
315 }
Evan Chenga8e29892007-01-19 07:51:42 +0000316 };
Devang Patel19974732007-05-03 01:11:54 +0000317 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000318}
319
Dale Johannesen8593e412007-04-29 19:19:30 +0000320/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000321void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000322#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000323 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000324 MBBI != E; ++MBBI) {
325 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000326 unsigned Align = MBB->getAlignment();
327 unsigned MBBId = MBB->getNumber();
328 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
329 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000330 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000331 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
332 CPUser &U = CPUsers[i];
333 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000334 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
335 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
336 UserOffset - CPEOffset;
337 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000338 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000339#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000340}
341
342/// print block size and offset information - debugging
343void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000344 DEBUG({
345 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
346 const BasicBlockInfo &BBI = BBInfo[J];
347 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
348 << " kb=" << unsigned(BBI.KnownBits)
349 << " ua=" << unsigned(BBI.Unalign)
350 << " pa=" << unsigned(BBI.PostAlign)
351 << format(" size=%#x\n", BBInfo[J].Size);
352 }
353 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000354}
355
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000356/// createARMConstantIslandPass - returns an instance of the constpool
357/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000358FunctionPass *llvm::createARMConstantIslandPass() {
359 return new ARMConstantIslands();
360}
361
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000362bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
363 MF = &mf;
364 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000365
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000366 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000367 << MCP->getConstants().size() << " CP entries, aligned to "
368 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000369
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000370 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
371 AFI = MF->getInfo<ARMFunctionInfo>();
372 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000373
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000374 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000375 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000376 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000377
378 HasFarJump = false;
379
Evan Chenga8e29892007-01-19 07:51:42 +0000380 // Renumber all of the machine basic blocks in the function, guaranteeing that
381 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000382 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000383
Jim Grosbach80697d12009-11-12 17:25:07 +0000384 // Try to reorder and otherwise adjust the block layout to make good use
385 // of the TB[BH] instructions.
386 bool MadeChange = false;
387 if (isThumb2 && AdjustJumpTableBlocks) {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000388 JumpTableFunctionScan();
389 MadeChange |= ReorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000390 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000391 T2JumpTables.clear();
392 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000393 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000394 }
395
Evan Chengd26b14c2009-07-31 18:28:05 +0000396 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000397 // This is so we can keep exact track of where the alignment padding goes.
398
Chris Lattner7d7dab02010-01-27 23:37:36 +0000399 // ARM and Thumb2 functions need to be 4-byte aligned.
400 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000401 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000402
Evan Chenga8e29892007-01-19 07:51:42 +0000403 // Perform the initial placement of the constant pool entries. To start with,
404 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000405 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000406 if (!MCP->isEmpty())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000407 DoInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000408
Evan Chenga8e29892007-01-19 07:51:42 +0000409 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000410 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000411
Evan Chenga8e29892007-01-19 07:51:42 +0000412 // Do the initial scan of the function, building up information about the
413 // sizes of each block, the location of all the water, and finding all of the
414 // constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000415 InitialFunctionScan(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000416 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000417 DEBUG(dumpBBs());
418
Bob Wilson84945262009-05-12 17:09:30 +0000419
Evan Chenged884f32007-04-03 23:39:48 +0000420 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000421 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000422
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000423 // Iteratively place constant pool entries and fix up branches until there
424 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000425 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000426 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000427 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000428 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000429 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000430 CPChange |= HandleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000431 if (CPChange && ++NoCPIters > 30)
432 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000433 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000434
Bob Wilsonb9239532009-10-15 20:49:47 +0000435 // Clear NewWaterList now. If we split a block for branches, it should
436 // appear as "new water" for the next iteration of constant pool placement.
437 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000438
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000439 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000440 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000441 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000442 BRChange |= FixUpImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000443 if (BRChange && ++NoBRIters > 30)
444 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000445 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000446
447 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000448 break;
449 MadeChange = true;
450 }
Evan Chenged884f32007-04-03 23:39:48 +0000451
Evan Chenga1efbbd2009-08-14 00:32:16 +0000452 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000453 if (isThumb2 && !STI->prefers32BitThumb())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000454 MadeChange |= OptimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000455
Dale Johannesen8593e412007-04-29 19:19:30 +0000456 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000457 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000458
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000459 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
460 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000461 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000462 MadeChange |= UndoLRSpillRestore();
463
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000464 // Save the mapping between original and cloned constpool entries.
465 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
466 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
467 const CPEntry & CPE = CPEntries[i][j];
468 AFI->recordCPEClone(i, CPE.CPI);
469 }
470 }
471
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000472 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000473
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000474 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000475 WaterList.clear();
476 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000477 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000478 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000479 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000480 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000481
482 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000483}
484
485/// DoInitialPlacement - Perform the initial placement of the constant pool
486/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000487void
488ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000489 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000490 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
491 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000492
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000493 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000494 unsigned MaxAlign = Log2_32(MF->getConstantPool()->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000495
496 // Mark the basic block as required by the const-pool.
497 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
498 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
499
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000500 // The function needs to be as aligned as the basic blocks. The linker may
501 // move functions around based on their alignment.
502 MF->EnsureAlignment(BB->getAlignment());
503
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000504 // Order the entries in BB by descending alignment. That ensures correct
505 // alignment of all entries as long as BB is sufficiently aligned. Keep
506 // track of the insertion point for each alignment. We are going to bucket
507 // sort the entries as they are created.
508 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000509
Evan Chenga8e29892007-01-19 07:51:42 +0000510 // Add all of the constants from the constant pool to the end block, use an
511 // identity mapping of CPI's to CPE's.
512 const std::vector<MachineConstantPoolEntry> &CPs =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000513 MF->getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000514
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000515 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000516 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000517 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000518 assert(Size >= 4 && "Too small constant pool entry");
519 unsigned Align = CPs[i].getAlignment();
520 assert(isPowerOf2_32(Align) && "Invalid alignment");
521 // Verify that all constant pool entries are a multiple of their alignment.
522 // If not, we would have to pad them out so that instructions stay aligned.
523 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
524
525 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
526 unsigned LogAlign = Log2_32(Align);
527 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000528 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000529 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000530 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000531 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000532
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000533 // Ensure that future entries with higher alignment get inserted before
534 // CPEMI. This is bucket sort with iterators.
535 for (unsigned a = LogAlign + 1; a < MaxAlign; ++a)
536 if (InsPoint[a] == InsAt)
537 InsPoint[a] = CPEMI;
538
Evan Chengc99ef082007-02-09 20:54:44 +0000539 // Add a new CPEntry, but no corresponding CPUser yet.
540 std::vector<CPEntry> CPEs;
541 CPEs.push_back(CPEntry(CPEMI, i));
542 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000543 ++NumCPEs;
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000544 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000545 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000546 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000547}
548
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000549/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000550/// into the block immediately after it.
551static bool BBHasFallthrough(MachineBasicBlock *MBB) {
552 // Get the next machine basic block in the function.
553 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000554 // Can't fall off end of function.
555 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000556 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000557
Chris Lattner7896c9f2009-12-03 00:50:42 +0000558 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000559 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
560 E = MBB->succ_end(); I != E; ++I)
561 if (*I == NextBB)
562 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000563
Evan Chenga8e29892007-01-19 07:51:42 +0000564 return false;
565}
566
Evan Chengc99ef082007-02-09 20:54:44 +0000567/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
568/// look up the corresponding CPEntry.
569ARMConstantIslands::CPEntry
570*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
571 const MachineInstr *CPEMI) {
572 std::vector<CPEntry> &CPEs = CPEntries[CPI];
573 // Number of entries per constpool index should be small, just do a
574 // linear search.
575 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
576 if (CPEs[i].CPEMI == CPEMI)
577 return &CPEs[i];
578 }
579 return NULL;
580}
581
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000582/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000583/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000584unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
585 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
586
587 // Everything is 4-byte aligned unless AlignConstantIslands is set.
588 if (!AlignConstantIslands)
589 return 2;
590
591 unsigned CPI = CPEMI->getOperand(1).getIndex();
592 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
593 unsigned Align = MCP->getConstants()[CPI].getAlignment();
594 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
595 return Log2_32(Align);
596}
597
Jim Grosbach80697d12009-11-12 17:25:07 +0000598/// JumpTableFunctionScan - Do a scan of the function, building up
599/// information about the sizes of each block and the locations of all
600/// the jump tables.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000601void ARMConstantIslands::JumpTableFunctionScan() {
602 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000603 MBBI != E; ++MBBI) {
604 MachineBasicBlock &MBB = *MBBI;
605
Jim Grosbach80697d12009-11-12 17:25:07 +0000606 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000607 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000608 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000609 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000610 }
611}
612
Evan Chenga8e29892007-01-19 07:51:42 +0000613/// InitialFunctionScan - Do the initial scan of the function, building up
614/// information about the sizes of each block, the location of all the water,
615/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000616void ARMConstantIslands::
617InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000618 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000619 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000620
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000621 // First thing, compute the size of all basic blocks, and see if the function
622 // has any inline assembly in it. If so, we have to be conservative about
623 // alignment assumptions, as we don't know for sure the size of any
624 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000625 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000626 ComputeBlockSize(I);
627
628 // The known bits of the entry block offset are determined by the function
629 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000630 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000631
632 // Compute block offsets and known bits.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000633 AdjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000634
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000635 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000636 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000637 MBBI != E; ++MBBI) {
638 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000639
Evan Chenga8e29892007-01-19 07:51:42 +0000640 // If this block doesn't fall through into the next MBB, then this is
641 // 'water' that a constant pool island could be placed.
642 if (!BBHasFallthrough(&MBB))
643 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000644
Evan Chenga8e29892007-01-19 07:51:42 +0000645 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
646 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000647 if (I->isDebugValue())
648 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000649
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000650 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000651 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000652 bool isCond = false;
653 unsigned Bits = 0;
654 unsigned Scale = 1;
655 int UOpc = Opc;
656 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000657 default:
658 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000659 case ARM::t2BR_JT:
660 T2JumpTables.push_back(I);
661 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000662 case ARM::Bcc:
663 isCond = true;
664 UOpc = ARM::B;
665 // Fallthrough
666 case ARM::B:
667 Bits = 24;
668 Scale = 4;
669 break;
670 case ARM::tBcc:
671 isCond = true;
672 UOpc = ARM::tB;
673 Bits = 8;
674 Scale = 2;
675 break;
676 case ARM::tB:
677 Bits = 11;
678 Scale = 2;
679 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000680 case ARM::t2Bcc:
681 isCond = true;
682 UOpc = ARM::t2B;
683 Bits = 20;
684 Scale = 2;
685 break;
686 case ARM::t2B:
687 Bits = 24;
688 Scale = 2;
689 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000690 }
Evan Chengb43216e2007-02-01 10:16:15 +0000691
692 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000693 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000694 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000695 }
696
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000697 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
698 PushPopMIs.push_back(I);
699
Evan Chengd3d9d662009-07-23 18:27:47 +0000700 if (Opc == ARM::CONSTPOOL_ENTRY)
701 continue;
702
Evan Chenga8e29892007-01-19 07:51:42 +0000703 // Scan the instructions for constant pool operands.
704 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000705 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000706 // We found one. The addressing mode tells us the max displacement
707 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000708
Evan Chenga8e29892007-01-19 07:51:42 +0000709 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000710 unsigned Bits = 0;
711 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000712 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000713 bool IsSoImm = false;
714
715 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000716 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000717 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000718 break;
719
720 // Taking the address of a CP entry.
721 case ARM::LEApcrel:
722 // This takes a SoImm, which is 8 bit immediate rotated. We'll
723 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000724 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000725 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000726 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000727 Scale = 4;
728 NegOk = true;
729 IsSoImm = true;
730 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000731 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000732 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000733 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000734 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000735 case ARM::tLEApcrel:
736 Bits = 8;
737 Scale = 4;
738 break;
739
Jim Grosbach3e556122010-10-26 22:37:02 +0000740 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000741 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000742 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000743 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000744 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000745 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000746
747 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000748 Bits = 8;
749 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000750 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000751
Jim Grosbache5165492009-11-09 00:11:35 +0000752 case ARM::VLDRD:
753 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000754 Bits = 8;
755 Scale = 4; // +-(offset_8*4)
756 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000757 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000758 }
Evan Chengb43216e2007-02-01 10:16:15 +0000759
Evan Chenga8e29892007-01-19 07:51:42 +0000760 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000761 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000762 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000763 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000764 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000765
766 // Increment corresponding CPEntry reference count.
767 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
768 assert(CPE && "Cannot find a corresponding CPEntry!");
769 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000770
Evan Chenga8e29892007-01-19 07:51:42 +0000771 // Instructions can only use one CP entry, don't bother scanning the
772 // rest of the operands.
773 break;
774 }
775 }
Evan Chenga8e29892007-01-19 07:51:42 +0000776 }
777}
778
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000779/// ComputeBlockSize - Compute the size and some alignment information for MBB.
780/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000781void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000782 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
783 BBI.Size = 0;
784 BBI.Unalign = 0;
785 BBI.PostAlign = 0;
786
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000787 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
788 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000789 BBI.Size += TII->GetInstSizeInBytes(I);
790 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
791 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000792 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000793 BBI.Unalign = isThumb ? 1 : 2;
794 }
795
796 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000797 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000798 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000799 MBB->getParent()->EnsureAlignment(2);
800 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000801}
802
Evan Chenga8e29892007-01-19 07:51:42 +0000803/// GetOffsetOf - Return the current offset of the specified machine instruction
804/// from the start of the function. This offset changes as stuff is moved
805/// around inside the function.
806unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
807 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000808
Evan Chenga8e29892007-01-19 07:51:42 +0000809 // The offset is composed of two things: the sum of the sizes of all MBB's
810 // before this instruction's block, and the offset from the start of the block
811 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000812 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000813
814 // Sum instructions before MI in MBB.
815 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
816 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
817 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000818 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000819 }
820}
821
822/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
823/// ID.
824static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
825 const MachineBasicBlock *RHS) {
826 return LHS->getNumber() < RHS->getNumber();
827}
828
829/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
830/// machine function, it upsets all of the block numbers. Renumber the blocks
831/// and update the arrays that parallel this numbering.
832void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000833 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000834 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000835
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000836 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000837 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000838 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000839
840 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000841 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000842 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000843 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
844 CompareMBBNumbers);
845 WaterList.insert(IP, NewBB);
846}
847
848
849/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000850/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000851/// account for this change and returns the newly created block.
852MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000853 MachineBasicBlock *OrigBB = MI->getParent();
854
855 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000856 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000857 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000858 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000859 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000860
Evan Chenga8e29892007-01-19 07:51:42 +0000861 // Splice the instructions starting with MI over to NewBB.
862 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000863
Evan Chenga8e29892007-01-19 07:51:42 +0000864 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000865 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000866 // There doesn't seem to be meaningful DebugInfo available; this doesn't
867 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000868 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000869 if (!isThumb)
870 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
871 else
872 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
873 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000874 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000875
Evan Chenga8e29892007-01-19 07:51:42 +0000876 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000877 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000878
Evan Chenga8e29892007-01-19 07:51:42 +0000879 // OrigBB branches to NewBB.
880 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000881
Evan Chenga8e29892007-01-19 07:51:42 +0000882 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883 // This is almost the same as UpdateForInsertedWaterBlock, except that
884 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000885 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000886
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000887 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000889 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000890
Bob Wilson84945262009-05-12 17:09:30 +0000891 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000892 // available water after it (but not if it's already there, which happens
893 // when splitting before a conditional branch that is followed by an
894 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000895 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000896 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
897 CompareMBBNumbers);
898 MachineBasicBlock* WaterBB = *IP;
899 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000900 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901 else
902 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000903 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000904
Dale Johannesen8086d582010-07-23 22:50:23 +0000905 // Figure out how large the OrigBB is. As the first half of the original
906 // block, it cannot contain a tablejump. The size includes
907 // the new jump we added. (It should be possible to do this without
908 // recounting everything, but it's very confusing, and this is rarely
909 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000910 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000911
Dale Johannesen8086d582010-07-23 22:50:23 +0000912 // Figure out how large the NewMBB is. As the second half of the original
913 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000914 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000915
Dale Johannesen99c49a42007-02-25 00:47:03 +0000916 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000917 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000918
919 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000920}
921
Dale Johannesen8593e412007-04-29 19:19:30 +0000922/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000923/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000924/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000925bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000926 unsigned TrialOffset, unsigned MaxDisp,
927 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000928 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
929 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000930 // Effectively, the valid range of displacements is 2 bytes smaller for such
931 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000932 unsigned TotalAdj = 0;
933 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000934 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000935 TotalAdj = 2;
936 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000937 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000938 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000939 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000940 TotalAdj += 2;
941 }
942
943 // In Thumb2 mode, later branch adjustments can shift instructions up and
944 // cause alignment change. In the worst case scenario this can cause the
945 // user's effective address to be subtracted by 2 and the CPE's address to
946 // be plus 2.
947 if (isThumb2 && TotalAdj != 4)
948 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000949
Dale Johannesen99c49a42007-02-25 00:47:03 +0000950 if (UserOffset <= TrialOffset) {
951 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000952 if (TrialOffset - UserOffset <= MaxDisp)
953 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000954 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000955 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000956 if (UserOffset - TrialOffset <= MaxDisp)
957 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000958 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000959 }
960 return false;
961}
962
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000963/// WaterIsInRange - Returns true if a CPE placed after the specified
964/// Water (a basic block) will be in range for the specific MI.
965
966bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000967 MachineBasicBlock* Water, CPUser &U) {
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000968 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000969
Dale Johannesend959aa42007-04-02 20:31:06 +0000970 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000971 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000972 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000973 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000974
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000975 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000976}
977
978/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000979/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000980bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000981 MachineInstr *CPEMI, unsigned MaxDisp,
982 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000983 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000984 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000985
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000986 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000987 DEBUG({
988 unsigned Block = MI->getParent()->getNumber();
989 const BasicBlockInfo &BBI = BBInfo[Block];
990 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
991 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000992 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000993 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000994 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
995 << format("CPE address=%#x offset=%+d: ", CPEOffset,
996 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000997 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000999
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001000 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001001}
1002
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001003#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001004/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1005/// unconditionally branches to its only successor.
1006static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1007 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1008 return false;
1009
1010 MachineBasicBlock *Succ = *MBB->succ_begin();
1011 MachineBasicBlock *Pred = *MBB->pred_begin();
1012 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001013 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1014 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001015 return PredMI->getOperand(0).getMBB() == Succ;
1016 return false;
1017}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001018#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001019
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001020void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001021 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1022 // Get the offset and known bits at the end of the layout predecessor.
1023 unsigned Offset = BBInfo[i - 1].postOffset();
1024 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
1025
1026 // Add padding before an aligned block. This may teach us more bits.
1027 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
1028 Offset = WorstCaseAlign(Offset, Align, KnownBits);
1029 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +00001030 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001031
1032 // This is where block i begins.
1033 BBInfo[i].Offset = Offset;
1034 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001035 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001036}
1037
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001038/// DecrementOldEntry - find the constant pool entry with index CPI
1039/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001040/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001041/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001042
Evan Chenged884f32007-04-03 23:39:48 +00001043bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001044 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001045 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1046 assert(CPE && "Unexpected!");
1047 if (--CPE->RefCount == 0) {
1048 RemoveDeadCPEMI(CPEMI);
1049 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001050 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001051 return true;
1052 }
1053 return false;
1054}
1055
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001056/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1057/// if not, see if an in-range clone of the CPE is in range, and if so,
1058/// change the data structures so the user references the clone. Returns:
1059/// 0 = no existing entry found
1060/// 1 = entry found, and there were no code insertions or deletions
1061/// 2 = entry found, and there were code insertions or deletions
1062int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1063{
1064 MachineInstr *UserMI = U.MI;
1065 MachineInstr *CPEMI = U.CPEMI;
1066
1067 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001068 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001069 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001070 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001071 }
1072
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001073 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001074 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001075 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1076 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1077 // We already tried this one
1078 if (CPEs[i].CPEMI == CPEMI)
1079 continue;
1080 // Removing CPEs can leave empty entries, skip
1081 if (CPEs[i].CPEMI == NULL)
1082 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001083 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001084 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001085 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001086 // Point the CPUser node to the replacement
1087 U.CPEMI = CPEs[i].CPEMI;
1088 // Change the CPI in the instruction operand to refer to the clone.
1089 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001090 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001091 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001092 break;
1093 }
1094 // Adjust the refcount of the clone...
1095 CPEs[i].RefCount++;
1096 // ...and the original. If we didn't remove the old entry, none of the
1097 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001098 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099 }
1100 }
1101 return 0;
1102}
1103
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001104/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1105/// the specific unconditional branch instruction.
1106static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001107 switch (Opc) {
1108 case ARM::tB:
1109 return ((1<<10)-1)*2;
1110 case ARM::t2B:
1111 return ((1<<23)-1)*2;
1112 default:
1113 break;
1114 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001115
David Goodwin5e47a9a2009-06-30 18:04:13 +00001116 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001117}
1118
Bob Wilsonb9239532009-10-15 20:49:47 +00001119/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001120/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001121/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001122/// is set to the WaterList entry. For Thumb, prefer water that will not
1123/// introduce padding to water that will. To ensure that this pass
1124/// terminates, the CPE location for a particular CPUser is only allowed to
1125/// move to a lower address, so search backward from the end of the list and
1126/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001127bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001128 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001129 if (WaterList.empty())
1130 return false;
1131
Bob Wilson32c50e82009-10-12 20:45:53 +00001132 bool FoundWaterThatWouldPad = false;
1133 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001134 for (water_iterator IP = prior(WaterList.end()),
1135 B = WaterList.begin();; --IP) {
1136 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001137 // Check if water is in range and is either at a lower address than the
1138 // current "high water mark" or a new water block that was created since
1139 // the previous iteration by inserting an unconditional branch. In the
1140 // latter case, we want to allow resetting the high water mark back to
1141 // this new water since we haven't seen it before. Inserting branches
1142 // should be relatively uncommon and when it does happen, we want to be
1143 // sure to take advantage of it for all the CPEs near that block, so that
1144 // we don't insert more branches than necessary.
1145 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1146 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1147 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001148 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001149 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001150 // This is valid Water, but would introduce padding. Remember
1151 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001152 if (!FoundWaterThatWouldPad) {
1153 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001154 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001155 }
Bob Wilson3b757352009-10-12 19:04:03 +00001156 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001157 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001158 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001159 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001160 }
Bob Wilson3b757352009-10-12 19:04:03 +00001161 if (IP == B)
1162 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001163 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001164 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001165 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001166 return true;
1167 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001168 return false;
1169}
1170
Bob Wilson84945262009-05-12 17:09:30 +00001171/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1173/// block is used if in range, and the conditional branch munged so control
1174/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001175/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001176/// block following which the new island can be inserted (the WaterList
1177/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001178void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001179 unsigned UserOffset,
1180 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001181 CPUser &U = CPUsers[CPUserIndex];
1182 MachineInstr *UserMI = U.MI;
1183 MachineInstr *CPEMI = U.CPEMI;
1184 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001185 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1186 unsigned OffsetOfNextBlock = UserBBI.postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001187
Bob Wilson36fa5322009-10-15 05:10:36 +00001188 // If the block does not end in an unconditional branch already, and if the
1189 // end of the block is within range, make new water there. (The addition
1190 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1191 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001192 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001193 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001194 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001195 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001196 if (&UserMBB->back() == UserMI)
1197 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001198 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001199 // Add an unconditional branch from UserMBB to fallthrough block.
1200 // Record it for branch lengthening; this new branch will not get out of
1201 // range, but if the preceding conditional branch is out of range, the
1202 // targets will be exchanged, and the altered branch may be out of
1203 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001204 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001205 if (!isThumb)
1206 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1207 else
1208 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1209 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001210 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001211 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001212 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001213 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001214 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001215 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001216 } else {
1217 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001218 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001219 // and constant pool entries are 4 bytes: if instruction I references
1220 // island CPE, and instruction I+1 references CPE', it will
1221 // not work well to put CPE as far forward as possible, since then
1222 // CPE' cannot immediately follow it (that location is 2 bytes
1223 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001224 // a new island. So, we make a first guess, then walk through the
1225 // instructions between the one currently being looked at and the
1226 // possible insertion point, and make sure any other instructions
1227 // that reference CPEs will be able to use the same island area;
1228 // if not, we back up the insertion point.
1229
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001230 // Try to split the block so it's fully aligned. Compute the latest split
1231 // point where we can add a 4-byte branch instruction, and then
1232 // WorstCaseAlign to LogAlign.
1233 unsigned LogAlign = UserMBB->getParent()->getAlignment();
1234 unsigned KnownBits = UserBBI.internalKnownBits();
1235 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1236 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1237 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1238 BaseInsertOffset));
1239
1240 // Account for alignment and unknown padding.
1241 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1242 BaseInsertOffset -= UPad;
1243
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001244 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001245 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001246 // island is handled inside OffsetIsInRange.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001247 BaseInsertOffset -= 4;
1248
1249 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1250 << " la=" << LogAlign
1251 << " kb=" << KnownBits
1252 << " up=" << UPad << '\n');
1253
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001254 // This could point off the end of the block if we've already got
1255 // constant pool entries following this block; only the last one is
1256 // in the water list. Back past any possible branches (allow for a
1257 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001258 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1259 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001260 (isThumb1 ? 6 : 8);
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001261 unsigned EndInsertOffset =
1262 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1263 CPEMI->getOperand(2).getImm();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001264 MachineBasicBlock::iterator MI = UserMI;
1265 ++MI;
1266 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001267 unsigned NumCPUsers = CPUsers.size();
1268 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001269 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001270 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001271 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001272 MI = llvm::next(MI)) {
1273 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001274 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001275 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001276 BaseInsertOffset -= 1u << LogAlign;
1277 EndInsertOffset -= 1u << LogAlign;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001278 }
1279 // This is overly conservative, as we don't account for CPEMIs
1280 // being reused within the block, but it doesn't matter much.
1281 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1282 CPUIndex++;
1283 }
Evan Cheng719510a2010-08-12 20:30:05 +00001284
1285 // Remember the last IT instruction.
1286 if (MI->getOpcode() == ARM::t2IT)
1287 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001288 }
Evan Cheng719510a2010-08-12 20:30:05 +00001289
Evan Cheng719510a2010-08-12 20:30:05 +00001290 --MI;
1291
1292 // Avoid splitting an IT block.
1293 if (LastIT) {
1294 unsigned PredReg = 0;
1295 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1296 if (CC != ARMCC::AL)
1297 MI = LastIT;
1298 }
1299 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001300 }
1301}
1302
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001303/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001304/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001305/// place in-range. Return true if we changed any addresses (thus must run
1306/// another pass of branch lengthening), false otherwise.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001307bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001308 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001309 MachineInstr *UserMI = U.MI;
1310 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001311 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001312 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001313 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001314 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001315 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001316
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001317 // See if the current entry is within range, or there is a clone of it
1318 // in range.
1319 int result = LookForExistingCPEntry(U, UserOffset);
1320 if (result==1) return false;
1321 else if (result==2) return true;
1322
1323 // No existing clone of this CPE is within range.
1324 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001325 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001326
Bob Wilsonf98032e2009-10-12 21:23:15 +00001327 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001328 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001329 MachineBasicBlock *NewMBB;
1330 water_iterator IP;
1331 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001332 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001333 MachineBasicBlock *WaterBB = *IP;
1334
1335 // If the original WaterList entry was "new water" on this iteration,
1336 // propagate that to the new island. This is just keeping NewWaterList
1337 // updated to match the WaterList, which will be updated below.
1338 if (NewWaterList.count(WaterBB)) {
1339 NewWaterList.erase(WaterBB);
1340 NewWaterList.insert(NewIsland);
1341 }
1342 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001343 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001344
1345 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001346 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001347 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001348 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001349
1350 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1351 // called while handling branches so that the water will be seen on the
1352 // next iteration for constant pools, but in this context, we don't want
1353 // it. Check for this so it will be removed from the WaterList.
1354 // Also remove any entry from NewWaterList.
1355 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1356 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1357 if (IP != WaterList.end())
1358 NewWaterList.erase(WaterBB);
1359
1360 // We are adding new water. Update NewWaterList.
1361 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001362 }
1363
Bob Wilsonb9239532009-10-15 20:49:47 +00001364 // Remove the original WaterList entry; we want subsequent insertions in
1365 // this vicinity to go after the one we're about to insert. This
1366 // considerably reduces the number of times we have to move the same CPE
1367 // more than once and is also important to ensure the algorithm terminates.
1368 if (IP != WaterList.end())
1369 WaterList.erase(IP);
1370
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001371 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001372 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373
1374 // Update internal data structures to account for the newly inserted MBB.
1375 UpdateForInsertedWaterBlock(NewIsland);
1376
1377 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001378 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001379
1380 // Now that we have an island to add the CPE to, clone the original CPE and
1381 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001382 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001383 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001384 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001385 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001386 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001387
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001388 // Mark the basic block as aligned as required by the const-pool entry.
1389 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001390
Evan Chenga8e29892007-01-19 07:51:42 +00001391 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001392 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001393 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001394
Evan Chenga8e29892007-01-19 07:51:42 +00001395 // Finally, change the CPI in the instruction operand to be ID.
1396 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001397 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001398 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001399 break;
1400 }
Bob Wilson84945262009-05-12 17:09:30 +00001401
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001402 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001403 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001404
Evan Chenga8e29892007-01-19 07:51:42 +00001405 return true;
1406}
1407
Evan Chenged884f32007-04-03 23:39:48 +00001408/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1409/// sizes and offsets of impacted basic blocks.
1410void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1411 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001412 unsigned Size = CPEMI->getOperand(2).getImm();
1413 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001414 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001415 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001416 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001417 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001418
1419 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1420 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001421 } else
1422 // Entries are sorted by descending alignment, so realign from the front.
1423 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1424
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001425 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001426 // An island has only one predecessor BB and one successor BB. Check if
1427 // this BB's predecessor jumps directly to this BB's successor. This
1428 // shouldn't happen currently.
1429 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1430 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001431}
1432
1433/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1434/// are zero.
1435bool ARMConstantIslands::RemoveUnusedCPEntries() {
1436 unsigned MadeChange = false;
1437 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1438 std::vector<CPEntry> &CPEs = CPEntries[i];
1439 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1440 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1441 RemoveDeadCPEMI(CPEs[j].CPEMI);
1442 CPEs[j].CPEMI = NULL;
1443 MadeChange = true;
1444 }
1445 }
Bob Wilson84945262009-05-12 17:09:30 +00001446 }
Evan Chenged884f32007-04-03 23:39:48 +00001447 return MadeChange;
1448}
1449
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001450/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001451/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001452bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1453 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001454 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001455 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001456 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001457
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001458 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001459 << " from BB#" << MI->getParent()->getNumber()
1460 << " max delta=" << MaxDisp
1461 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1462 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001463
Dale Johannesen8593e412007-04-29 19:19:30 +00001464 if (BrOffset <= DestOffset) {
1465 // Branch before the Dest.
1466 if (DestOffset-BrOffset <= MaxDisp)
1467 return true;
1468 } else {
1469 if (BrOffset-DestOffset <= MaxDisp)
1470 return true;
1471 }
1472 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001473}
1474
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001475/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1476/// away to fit in its displacement field.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001477bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001478 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001479 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001480
Evan Chengc0dbec72007-01-31 19:57:44 +00001481 // Check to see if the DestBB is already in-range.
1482 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001483 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001484
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001485 if (!Br.isCond)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001486 return FixUpUnconditionalBr(Br);
1487 return FixUpConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001488}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001489
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001490/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1491/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001492/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001493/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001494bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001495ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001496 MachineInstr *MI = Br.MI;
1497 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001498 if (!isThumb1)
1499 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001500
1501 // Use BL to implement far jump.
1502 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001503 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001504 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001505 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001506 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001507 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001508
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001509 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001510
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001511 return true;
1512}
1513
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001514/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001515/// far away to fit in its displacement field. It is converted to an inverse
1516/// conditional branch + an unconditional branch to the destination.
1517bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001518ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001519 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001520 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001521
Bob Wilson39bf0512009-05-12 17:35:29 +00001522 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001523 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001524 // blt L1
1525 // =>
1526 // bge L2
1527 // b L1
1528 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001529 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001530 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001531 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001532
1533 // If the branch is at the end of its MBB and that has a fall-through block,
1534 // direct the updated conditional branch to the fall-through block. Otherwise,
1535 // split the MBB before the next instruction.
1536 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001537 MachineInstr *BMI = &MBB->back();
1538 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001539
Dan Gohmanfe601042010-06-22 15:08:57 +00001540 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001541 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001542 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001543 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001544 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001545 // condition and swap destinations:
1546 // beq L1
1547 // b L2
1548 // =>
1549 // bne L2
1550 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001551 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001552 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001553 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001554 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001555 BMI->getOperand(0).setMBB(DestBB);
1556 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001557 MI->getOperand(1).setImm(CC);
1558 return true;
1559 }
1560 }
1561 }
1562
1563 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001564 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001565 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001566 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001567 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001568 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001569 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001570 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001571 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001572 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001573
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001574 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001575 << " also invert condition and change dest. to BB#"
1576 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001577
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001578 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001579 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001580 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001581 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001582 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001583 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001584 if (isThumb)
1585 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1586 .addImm(ARMCC::AL).addReg(0);
1587 else
1588 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001589 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001590 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001591 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001592
1593 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001594 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001595 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001596 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001597 return true;
1598}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001599
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001600/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001601/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1602/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001603bool ARMConstantIslands::UndoLRSpillRestore() {
1604 bool MadeChange = false;
1605 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1606 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001607 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001608 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001609 MI->getOperand(2).getReg() == ARM::PC &&
1610 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001611 // Create the new insn and copy the predicate from the old.
1612 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1613 .addOperand(MI->getOperand(0))
1614 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001615 MI->eraseFromParent();
1616 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001617 }
1618 }
1619 return MadeChange;
1620}
Evan Cheng5657c012009-07-29 02:18:14 +00001621
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001622bool ARMConstantIslands::OptimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001623 bool MadeChange = false;
1624
1625 // Shrink ADR and LDR from constantpool.
1626 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1627 CPUser &U = CPUsers[i];
1628 unsigned Opcode = U.MI->getOpcode();
1629 unsigned NewOpc = 0;
1630 unsigned Scale = 1;
1631 unsigned Bits = 0;
1632 switch (Opcode) {
1633 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001634 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001635 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1636 NewOpc = ARM::tLEApcrel;
1637 Bits = 8;
1638 Scale = 4;
1639 }
1640 break;
1641 case ARM::t2LDRpci:
1642 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1643 NewOpc = ARM::tLDRpci;
1644 Bits = 8;
1645 Scale = 4;
1646 }
1647 break;
1648 }
1649
1650 if (!NewOpc)
1651 continue;
1652
1653 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1654 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1655 // FIXME: Check if offset is multiple of scale if scale is not 4.
1656 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1657 U.MI->setDesc(TII->get(NewOpc));
1658 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001659 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001660 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001661 ++NumT2CPShrunk;
1662 MadeChange = true;
1663 }
1664 }
1665
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001666 MadeChange |= OptimizeThumb2Branches();
1667 MadeChange |= OptimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001668 return MadeChange;
1669}
1670
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001671bool ARMConstantIslands::OptimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001672 bool MadeChange = false;
1673
1674 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1675 ImmBranch &Br = ImmBranches[i];
1676 unsigned Opcode = Br.MI->getOpcode();
1677 unsigned NewOpc = 0;
1678 unsigned Scale = 1;
1679 unsigned Bits = 0;
1680 switch (Opcode) {
1681 default: break;
1682 case ARM::t2B:
1683 NewOpc = ARM::tB;
1684 Bits = 11;
1685 Scale = 2;
1686 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001687 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001688 NewOpc = ARM::tBcc;
1689 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001690 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001691 break;
1692 }
Evan Chengde17fb62009-10-31 23:46:45 +00001693 }
1694 if (NewOpc) {
1695 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1696 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1697 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1698 Br.MI->setDesc(TII->get(NewOpc));
1699 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001700 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001701 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001702 ++NumT2BrShrunk;
1703 MadeChange = true;
1704 }
1705 }
1706
1707 Opcode = Br.MI->getOpcode();
1708 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001709 continue;
1710
Evan Chengde17fb62009-10-31 23:46:45 +00001711 NewOpc = 0;
1712 unsigned PredReg = 0;
1713 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1714 if (Pred == ARMCC::EQ)
1715 NewOpc = ARM::tCBZ;
1716 else if (Pred == ARMCC::NE)
1717 NewOpc = ARM::tCBNZ;
1718 if (!NewOpc)
1719 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001720 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001721 // Check if the distance is within 126. Subtract starting offset by 2
1722 // because the cmp will be eliminated.
1723 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001724 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001725 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001726 MachineBasicBlock::iterator CmpMI = Br.MI;
1727 if (CmpMI != Br.MI->getParent()->begin()) {
1728 --CmpMI;
1729 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1730 unsigned Reg = CmpMI->getOperand(0).getReg();
1731 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1732 if (Pred == ARMCC::AL &&
1733 CmpMI->getOperand(1).getImm() == 0 &&
1734 isARMLowRegister(Reg)) {
1735 MachineBasicBlock *MBB = Br.MI->getParent();
1736 MachineInstr *NewBR =
1737 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1738 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1739 CmpMI->eraseFromParent();
1740 Br.MI->eraseFromParent();
1741 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001742 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001743 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001744 ++NumCBZ;
1745 MadeChange = true;
1746 }
Evan Chengde17fb62009-10-31 23:46:45 +00001747 }
1748 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001749 }
1750 }
1751
1752 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001753}
1754
Evan Chenga1efbbd2009-08-14 00:32:16 +00001755/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1756/// jumptables when it's possible.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001757bool ARMConstantIslands::OptimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001758 bool MadeChange = false;
1759
1760 // FIXME: After the tables are shrunk, can we get rid some of the
1761 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001762 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001763 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001764
Evan Cheng5657c012009-07-29 02:18:14 +00001765 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1766 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1767 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001768 const MCInstrDesc &MCID = MI->getDesc();
1769 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001770 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001771 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1772 unsigned JTI = JTOP.getIndex();
1773 assert(JTI < JT.size());
1774
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001775 bool ByteOk = true;
1776 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001777 unsigned JTOffset = GetOffsetOf(MI) + 4;
1778 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001779 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1780 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001781 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001782 // Negative offset is not ok. FIXME: We should change BB layout to make
1783 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001784 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001785 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001786 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001787 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001788 HalfWordOk = false;
1789 if (!ByteOk && !HalfWordOk)
1790 break;
1791 }
1792
1793 if (ByteOk || HalfWordOk) {
1794 MachineBasicBlock *MBB = MI->getParent();
1795 unsigned BaseReg = MI->getOperand(0).getReg();
1796 bool BaseRegKill = MI->getOperand(0).isKill();
1797 if (!BaseRegKill)
1798 continue;
1799 unsigned IdxReg = MI->getOperand(1).getReg();
1800 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001801
1802 // Scan backwards to find the instruction that defines the base
1803 // register. Due to post-RA scheduling, we can't count on it
1804 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001805 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001806 MachineBasicBlock::iterator B = MBB->begin();
1807 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1808 --PrevI;
1809
1810 // If for some reason we didn't find it, we can't do anything, so
1811 // just skip this one.
1812 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001813 continue;
1814
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001815 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001816 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001817 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001818 // Make sure it only defines the base register and kills any uses
1819 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001820 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1821 const MachineOperand &MO = AddrMI->getOperand(k);
1822 if (!MO.isReg() || !MO.getReg())
1823 continue;
1824 if (MO.isDef() && MO.getReg() != BaseReg) {
1825 OptOk = false;
1826 break;
1827 }
1828 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1829 OptOk = false;
1830 break;
1831 }
1832 }
1833 if (!OptOk)
1834 continue;
1835
Owen Anderson6b8719f2010-12-13 22:51:08 +00001836 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001837 // that gave us the initial base register definition.
1838 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1839 ;
1840
Owen Anderson6b8719f2010-12-13 22:51:08 +00001841 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001842 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001843 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001844 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001845 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001846 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001847 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001848
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001849 if (!OptOk)
1850 continue;
1851
Jim Grosbachd092a872010-11-29 21:28:32 +00001852 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001853 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1854 .addReg(IdxReg, getKillRegState(IdxRegKill))
1855 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1856 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1857 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1858 // is 2-byte aligned. For now, asm printer will fix it up.
1859 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1860 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1861 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1862 OrigSize += TII->GetInstSizeInBytes(MI);
1863
1864 AddrMI->eraseFromParent();
1865 LeaMI->eraseFromParent();
1866 MI->eraseFromParent();
1867
1868 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001869 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001870 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001871
1872 ++NumTBs;
1873 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001874 }
1875 }
1876
1877 return MadeChange;
1878}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001879
Jim Grosbach9249efe2009-11-16 18:55:47 +00001880/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1881/// jump tables always branch forwards, since that's what tbb and tbh need.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001882bool ARMConstantIslands::ReorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001883 bool MadeChange = false;
1884
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001885 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001886 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001887
Jim Grosbach80697d12009-11-12 17:25:07 +00001888 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1889 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1890 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001891 const MCInstrDesc &MCID = MI->getDesc();
1892 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001893 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001894 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1895 unsigned JTI = JTOP.getIndex();
1896 assert(JTI < JT.size());
1897
1898 // We prefer if target blocks for the jump table come after the jump
1899 // instruction so we can use TB[BH]. Loop through the target blocks
1900 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001901 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001902 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1903 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1904 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001905 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001906
Jim Grosbach08cbda52009-11-16 18:58:52 +00001907 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001908 // The destination precedes the switch. Try to move the block forward
1909 // so we have a positive offset.
1910 MachineBasicBlock *NewBB =
1911 AdjustJTTargetBlockForward(MBB, MI->getParent());
1912 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001913 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001914 MadeChange = true;
1915 }
1916 }
1917 }
1918
1919 return MadeChange;
1920}
1921
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001922MachineBasicBlock *ARMConstantIslands::
1923AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1924{
Jim Grosbach03e2d442010-07-07 22:53:35 +00001925 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001926 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001927 // table that branches back to the actual target. This is a very simple
1928 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001929 MachineBasicBlock *TBB = 0, *FBB = 0;
1930 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001931 SmallVector<MachineOperand, 4> CondPrior;
1932 MachineFunction::iterator BBi = BB;
1933 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001934
Jim Grosbachca215e72009-11-16 17:10:56 +00001935 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001936 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001937
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001938 // If the block ends in an unconditional branch, move it. The prior block
1939 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001940 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001941 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001942 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001943 BB->moveAfter(JTBB);
1944 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001945 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001946 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001947 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001948 ++NumJTMoved;
1949 return NULL;
1950 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001951
1952 // Create a new MBB for the code after the jump BB.
1953 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001954 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001955 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001956 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001957
1958 // Add an unconditional branch from NewBB to BB.
1959 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1960 // correspond directly to anything in the source.
1961 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001962 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1963 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001964
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001965 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001966 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001967
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001968 // Update the CFG.
1969 NewBB->addSuccessor(BB);
1970 JTBB->removeSuccessor(BB);
1971 JTBB->addSuccessor(NewBB);
1972
Jim Grosbach80697d12009-11-12 17:25:07 +00001973 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001974 return NewBB;
1975}