blob: b7b391d309ca4baa0c6bc6d11670eb8dc93a4d89 [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 Cheng719510a2010-08-12 20:30:05 +000019#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000020#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000021#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000024#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000026#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000027#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000028#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
Jakob Stoklund Olesenf5bb45f2011-12-16 16:07:41 +000054// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000055static cl::opt<bool>
Jakob Stoklund Olesenb6ff6ec2011-12-15 22:14:45 +000056AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000057 cl::desc("Align constant islands in code"));
58
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000059/// UnknownPadding - Return the worst case padding that could result from
60/// unknown offset bits. This does not include alignment padding caused by
61/// known offset bits.
62///
63/// @param LogAlign log2(alignment)
64/// @param KnownBits Number of known low offset bits.
65static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
66 if (KnownBits < LogAlign)
67 return (1u << LogAlign) - (1u << KnownBits);
68 return 0;
69}
70
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000071/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
72/// add padding such that:
73///
74/// 1. The result is aligned to 1 << LogAlign.
75///
76/// 2. No other value of the unknown bits would require more padding.
77///
78/// This may add more padding than is required to satisfy just one of the
79/// constraints. It is necessary to compute alignment this way to guarantee
80/// that we don't underestimate the padding before an aligned block. If the
81/// real padding before a block is larger than we think, constant pool entries
82/// may go out of range.
83static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
84 unsigned KnownBits) {
85 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000086 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000087
88 // Then align the result.
89 return RoundUpToAlignment(Offset, 1u << LogAlign);
90}
91
Evan Chenga8e29892007-01-19 07:51:42 +000092namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000093 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000094 /// requires constant pool entries to be scattered among the instructions
95 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000096 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000097 /// special instructions.
98 ///
99 /// The terminology used in this pass includes:
100 /// Islands - Clumps of constants placed in the function.
101 /// Water - Potential places where an island could be formed.
102 /// CPE - A constant pool entry that has been placed somewhere, which
103 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000104 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000105 /// BasicBlockInfo - Information about the offset and size of a single
106 /// basic block.
107 struct BasicBlockInfo {
108 /// Offset - Distance from the beginning of the function to the beginning
109 /// of this basic block.
110 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000111 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000112 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000113
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000114 /// Size - Size of the basic block in bytes. If the block contains
115 /// inline assembly, this is a worst case estimate.
116 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000117 /// The size does not include any alignment padding whether from the
118 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000119 unsigned Size;
120
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000121 /// KnownBits - The number of low bits in Offset that are known to be
122 /// exact. The remaining bits of Offset are an upper bound.
123 uint8_t KnownBits;
124
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000125 /// Unalign - When non-zero, the block contains instructions (inline asm)
126 /// of unknown size. The real size may be smaller than Size bytes by a
127 /// multiple of 1 << Unalign.
128 uint8_t Unalign;
129
130 /// PostAlign - When non-zero, the block terminator contains a .align
131 /// directive, so the end of the block is aligned to 1 << PostAlign
132 /// bytes.
133 uint8_t PostAlign;
134
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000135 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
136 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000137
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000138 /// Compute the number of known offset bits internally to this block.
139 /// This number should be used to predict worst case padding when
140 /// splitting the block.
141 unsigned internalKnownBits() const {
142 return Unalign ? Unalign : KnownBits;
143 }
144
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000145 /// Compute the offset immediately following this block. If LogAlign is
146 /// specified, return the offset the successor block will get if it has
147 /// this alignment.
148 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000149 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000150 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
151 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000152 return PO;
153 // Add alignment padding from the terminator.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000154 return WorstCaseAlign(PO, LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000155 }
156
157 /// Compute the number of known low bits of postOffset. If this block
158 /// contains inline asm, the number of known bits drops to the
159 /// instruction alignment. An aligned terminator may increase the number
160 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000161 /// If LogAlign is given, also consider the alignment of the next block.
162 unsigned postKnownBits(unsigned LogAlign = 0) const {
163 return std::max(std::max(unsigned(PostAlign), LogAlign),
164 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000165 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000166 };
167
168 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000169
Evan Chenga8e29892007-01-19 07:51:42 +0000170 /// WaterList - A sorted list of basic blocks where islands could be placed
171 /// (i.e. blocks that don't fall through to the following block, due
172 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000173 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000174
Bob Wilsonb9239532009-10-15 20:49:47 +0000175 /// NewWaterList - The subset of WaterList that was created since the
176 /// previous iteration by inserting unconditional branches.
177 SmallSet<MachineBasicBlock*, 4> NewWaterList;
178
Bob Wilson034de5f2009-10-12 18:52:13 +0000179 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
180
Evan Chenga8e29892007-01-19 07:51:42 +0000181 /// CPUser - One user of a constant pool, keeping the machine instruction
182 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000183 /// allowed from the instruction to the CP. The HighWaterMark records the
184 /// highest basic block where a new CPEntry can be placed. To ensure this
185 /// pass terminates, the CP entries are initially placed at the end of the
186 /// function and then move monotonically to lower addresses. The
187 /// exception to this rule is when the current CP entry for a particular
188 /// CPUser is out of range, but there is another CP entry for the same
189 /// constant value in range. We want to use the existing in-range CP
190 /// entry, but if it later moves out of range, the search for new water
191 /// should resume where it left off. The HighWaterMark is used to record
192 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000193 struct CPUser {
194 MachineInstr *MI;
195 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000196 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000197 private:
Evan Chenga8e29892007-01-19 07:51:42 +0000198 unsigned MaxDisp;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000199 public:
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000200 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000201 bool IsSoImm;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000202 bool KnownAlignment;
Evan Chengd3d9d662009-07-23 18:27:47 +0000203 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
204 bool neg, bool soimm)
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000205 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
206 KnownAlignment(false) {
Bob Wilson549dda92009-10-15 05:52:29 +0000207 HighWaterMark = CPEMI->getParent();
208 }
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000209 /// getMaxDisp - Returns the maximum displacement supported by MI.
210 /// Correct for unknown alignment.
211 unsigned getMaxDisp() const {
212 return KnownAlignment ? MaxDisp : MaxDisp - 2;
213 }
Evan Chenga8e29892007-01-19 07:51:42 +0000214 };
Bob Wilson84945262009-05-12 17:09:30 +0000215
Evan Chenga8e29892007-01-19 07:51:42 +0000216 /// CPUsers - Keep track of all of the machine instructions that use various
217 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000218 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000219
Evan Chengc99ef082007-02-09 20:54:44 +0000220 /// CPEntry - One per constant pool entry, keeping the machine instruction
221 /// pointer, the constpool index, and the number of CPUser's which
222 /// reference this entry.
223 struct CPEntry {
224 MachineInstr *CPEMI;
225 unsigned CPI;
226 unsigned RefCount;
227 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
228 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
229 };
230
231 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000232 /// instructions. For each original constpool index (i.e. those that
233 /// existed upon entry to this pass), it keeps a vector of entries.
234 /// Original elements are cloned as we go along; the clones are
235 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000236 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000237
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238 /// ImmBranch - One per immediate branch, keeping the machine instruction
239 /// pointer, conditional or unconditional, the max displacement,
240 /// and (if isCond is true) the corresponding unconditional branch
241 /// opcode.
242 struct ImmBranch {
243 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000244 unsigned MaxDisp : 31;
245 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000246 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000247 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
248 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000249 };
250
Evan Cheng2706f972007-05-16 05:14:06 +0000251 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000252 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000253 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000254
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000255 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
256 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000257 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000258
Evan Cheng5657c012009-07-29 02:18:14 +0000259 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
260 SmallVector<MachineInstr*, 4> T2JumpTables;
261
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000262 /// HasFarJump - True if any far jump instruction has been emitted during
263 /// the branch fix up pass.
264 bool HasFarJump;
265
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000266 MachineFunction *MF;
267 MachineConstantPool *MCP;
Craig Topperacf20772012-03-25 23:49:58 +0000268 const ARMBaseInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000269 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000270 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000271 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000272 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000273 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000274 public:
Devang Patel19974732007-05-03 01:11:54 +0000275 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000276 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000277
Evan Cheng5657c012009-07-29 02:18:14 +0000278 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000279
280 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000281 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000282 }
Bob Wilson84945262009-05-12 17:09:30 +0000283
Evan Chenga8e29892007-01-19 07:51:42 +0000284 private:
Jim Grosbach7a465252012-03-23 23:07:03 +0000285 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000286 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000287 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach7a465252012-03-23 23:07:03 +0000288 void scanFunctionJumpTables();
289 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
290 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
291 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
292 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
293 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
294 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
295 bool findAvailableWater(CPUser&U, unsigned UserOffset,
296 water_iterator &WaterIter);
297 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000298 MachineBasicBlock *&NewMBB);
Jim Grosbach7a465252012-03-23 23:07:03 +0000299 bool handleConstantPoolUser(unsigned CPUserIndex);
300 void removeDeadCPEMI(MachineInstr *CPEMI);
301 bool removeUnusedCPEntries();
302 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
303 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
304 bool DoDump = false);
305 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000306 CPUser &U, unsigned &Growth);
Jim Grosbach7a465252012-03-23 23:07:03 +0000307 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
308 bool fixupImmediateBr(ImmBranch &Br);
309 bool fixupConditionalBr(ImmBranch &Br);
310 bool fixupUnconditionalBr(ImmBranch &Br);
311 bool undoLRSpillRestore();
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000312 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach7a465252012-03-23 23:07:03 +0000313 bool optimizeThumb2Instructions();
314 bool optimizeThumb2Branches();
315 bool reorderThumb2JumpTables();
316 bool optimizeThumb2JumpTables();
317 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000318 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000319
Jim Grosbach7a465252012-03-23 23:07:03 +0000320 void computeBlockSize(MachineBasicBlock *MBB);
321 unsigned getOffsetOf(MachineInstr *MI) const;
322 unsigned getUserOffset(CPUser&) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000323 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000324 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000325
Jim Grosbach7a465252012-03-23 23:07:03 +0000326 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000327 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach7a465252012-03-23 23:07:03 +0000328 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000329 const CPUser &U) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000330 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000331 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000332 }
Evan Chenga8e29892007-01-19 07:51:42 +0000333 };
Devang Patel19974732007-05-03 01:11:54 +0000334 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000335}
336
Dale Johannesen8593e412007-04-29 19:19:30 +0000337/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000338void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000339#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000340 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000341 MBBI != E; ++MBBI) {
342 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000343 unsigned Align = MBB->getAlignment();
344 unsigned MBBId = MBB->getNumber();
345 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
346 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000347 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000348 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
349 CPUser &U = CPUsers[i];
Jim Grosbach7a465252012-03-23 23:07:03 +0000350 unsigned UserOffset = getUserOffset(U);
351 assert(isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp(),
352 U.NegOk) && "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000353 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000354#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000355}
356
357/// print block size and offset information - debugging
358void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000359 DEBUG({
360 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
361 const BasicBlockInfo &BBI = BBInfo[J];
362 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
363 << " kb=" << unsigned(BBI.KnownBits)
364 << " ua=" << unsigned(BBI.Unalign)
365 << " pa=" << unsigned(BBI.PostAlign)
366 << format(" size=%#x\n", BBInfo[J].Size);
367 }
368 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000369}
370
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000371/// createARMConstantIslandPass - returns an instance of the constpool
372/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000373FunctionPass *llvm::createARMConstantIslandPass() {
374 return new ARMConstantIslands();
375}
376
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000377bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
378 MF = &mf;
379 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000380
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000381 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000382 << MCP->getConstants().size() << " CP entries, aligned to "
383 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000384
Craig Topperacf20772012-03-25 23:49:58 +0000385 TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000386 AFI = MF->getInfo<ARMFunctionInfo>();
387 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000388
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000389 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000390 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000391 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000392
393 HasFarJump = false;
394
Evan Chenga8e29892007-01-19 07:51:42 +0000395 // Renumber all of the machine basic blocks in the function, guaranteeing that
396 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000397 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000398
Jim Grosbach80697d12009-11-12 17:25:07 +0000399 // Try to reorder and otherwise adjust the block layout to make good use
400 // of the TB[BH] instructions.
401 bool MadeChange = false;
402 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000403 scanFunctionJumpTables();
404 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000405 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000406 T2JumpTables.clear();
407 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000408 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000409 }
410
Evan Chengd26b14c2009-07-31 18:28:05 +0000411 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000412 // This is so we can keep exact track of where the alignment padding goes.
413
Chris Lattner7d7dab02010-01-27 23:37:36 +0000414 // ARM and Thumb2 functions need to be 4-byte aligned.
415 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000416 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000417
Evan Chenga8e29892007-01-19 07:51:42 +0000418 // Perform the initial placement of the constant pool entries. To start with,
419 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000420 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000421 if (!MCP->isEmpty())
Jim Grosbach7a465252012-03-23 23:07:03 +0000422 doInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000423
Evan Chenga8e29892007-01-19 07:51:42 +0000424 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000425 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000426
Evan Chenga8e29892007-01-19 07:51:42 +0000427 // Do the initial scan of the function, building up information about the
428 // sizes of each block, the location of all the water, and finding all of the
429 // constant pool users.
Jim Grosbach7a465252012-03-23 23:07:03 +0000430 initializeFunctionInfo(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000431 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000432 DEBUG(dumpBBs());
433
Bob Wilson84945262009-05-12 17:09:30 +0000434
Evan Chenged884f32007-04-03 23:39:48 +0000435 /// Remove dead constant pool entries.
Jim Grosbach7a465252012-03-23 23:07:03 +0000436 MadeChange |= removeUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000437
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000438 // Iteratively place constant pool entries and fix up branches until there
439 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000440 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000441 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000442 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000443 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000444 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000445 CPChange |= handleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000446 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000447 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000448 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000449
Bob Wilsonb9239532009-10-15 20:49:47 +0000450 // Clear NewWaterList now. If we split a block for branches, it should
451 // appear as "new water" for the next iteration of constant pool placement.
452 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000453
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000454 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000455 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000456 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000457 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000458 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000459 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000460 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000461
462 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000463 break;
464 MadeChange = true;
465 }
Evan Chenged884f32007-04-03 23:39:48 +0000466
Evan Chenga1efbbd2009-08-14 00:32:16 +0000467 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000468 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach7a465252012-03-23 23:07:03 +0000469 MadeChange |= optimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000470
Dale Johannesen8593e412007-04-29 19:19:30 +0000471 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000472 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000473
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000474 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
475 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000476 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach7a465252012-03-23 23:07:03 +0000477 MadeChange |= undoLRSpillRestore();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000478
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000479 // Save the mapping between original and cloned constpool entries.
480 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
481 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
482 const CPEntry & CPE = CPEntries[i][j];
483 AFI->recordCPEClone(i, CPE.CPI);
484 }
485 }
486
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000487 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000488
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000489 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000490 WaterList.clear();
491 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000492 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000493 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000494 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000495 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000496
497 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000498}
499
Jim Grosbach7a465252012-03-23 23:07:03 +0000500/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Chenga8e29892007-01-19 07:51:42 +0000501/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000502void
Jim Grosbach7a465252012-03-23 23:07:03 +0000503ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000504 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000505 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
506 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000507
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000508 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000509 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000510
511 // Mark the basic block as required by the const-pool.
512 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
513 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
514
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000515 // The function needs to be as aligned as the basic blocks. The linker may
516 // move functions around based on their alignment.
517 MF->EnsureAlignment(BB->getAlignment());
518
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000519 // Order the entries in BB by descending alignment. That ensures correct
520 // alignment of all entries as long as BB is sufficiently aligned. Keep
521 // track of the insertion point for each alignment. We are going to bucket
522 // sort the entries as they are created.
523 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000524
Evan Chenga8e29892007-01-19 07:51:42 +0000525 // Add all of the constants from the constant pool to the end block, use an
526 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000527 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000528
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000529 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000530 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000531 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000532 assert(Size >= 4 && "Too small constant pool entry");
533 unsigned Align = CPs[i].getAlignment();
534 assert(isPowerOf2_32(Align) && "Invalid alignment");
535 // Verify that all constant pool entries are a multiple of their alignment.
536 // If not, we would have to pad them out so that instructions stay aligned.
537 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
538
539 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
540 unsigned LogAlign = Log2_32(Align);
541 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000542 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000543 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000544 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000545 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000546
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000547 // Ensure that future entries with higher alignment get inserted before
548 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000549 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000550 if (InsPoint[a] == InsAt)
551 InsPoint[a] = CPEMI;
552
Evan Chengc99ef082007-02-09 20:54:44 +0000553 // Add a new CPEntry, but no corresponding CPUser yet.
554 std::vector<CPEntry> CPEs;
555 CPEs.push_back(CPEntry(CPEMI, i));
556 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000557 ++NumCPEs;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000558 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
559 << Size << ", align = " << Align <<'\n');
Evan Chenga8e29892007-01-19 07:51:42 +0000560 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000561 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000562}
563
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000564/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000565/// into the block immediately after it.
566static bool BBHasFallthrough(MachineBasicBlock *MBB) {
567 // Get the next machine basic block in the function.
568 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000569 // Can't fall off end of function.
570 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000571 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000572
Chris Lattner7896c9f2009-12-03 00:50:42 +0000573 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000574 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
575 E = MBB->succ_end(); I != E; ++I)
576 if (*I == NextBB)
577 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000578
Evan Chenga8e29892007-01-19 07:51:42 +0000579 return false;
580}
581
Evan Chengc99ef082007-02-09 20:54:44 +0000582/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
583/// look up the corresponding CPEntry.
584ARMConstantIslands::CPEntry
585*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
586 const MachineInstr *CPEMI) {
587 std::vector<CPEntry> &CPEs = CPEntries[CPI];
588 // Number of entries per constpool index should be small, just do a
589 // linear search.
590 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
591 if (CPEs[i].CPEMI == CPEMI)
592 return &CPEs[i];
593 }
594 return NULL;
595}
596
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000597/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000598/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000599unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
600 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
601
602 // Everything is 4-byte aligned unless AlignConstantIslands is set.
603 if (!AlignConstantIslands)
604 return 2;
605
606 unsigned CPI = CPEMI->getOperand(1).getIndex();
607 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
608 unsigned Align = MCP->getConstants()[CPI].getAlignment();
609 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
610 return Log2_32(Align);
611}
612
Jim Grosbach7a465252012-03-23 23:07:03 +0000613/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach80697d12009-11-12 17:25:07 +0000614/// information about the sizes of each block and the locations of all
615/// the jump tables.
Jim Grosbach7a465252012-03-23 23:07:03 +0000616void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000617 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000618 MBBI != E; ++MBBI) {
619 MachineBasicBlock &MBB = *MBBI;
620
Jim Grosbach80697d12009-11-12 17:25:07 +0000621 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000622 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000623 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000624 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000625 }
626}
627
Jim Grosbach7a465252012-03-23 23:07:03 +0000628/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Chenga8e29892007-01-19 07:51:42 +0000629/// information about the sizes of each block, the location of all the water,
630/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000631void ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +0000632initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000633 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000634 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000635
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000636 // First thing, compute the size of all basic blocks, and see if the function
637 // has any inline assembly in it. If so, we have to be conservative about
638 // alignment assumptions, as we don't know for sure the size of any
639 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000640 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach7a465252012-03-23 23:07:03 +0000641 computeBlockSize(I);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000642
643 // The known bits of the entry block offset are determined by the function
644 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000645 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000646
647 // Compute block offsets and known bits.
Jim Grosbach7a465252012-03-23 23:07:03 +0000648 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000649
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000650 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000651 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000652 MBBI != E; ++MBBI) {
653 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000654
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // If this block doesn't fall through into the next MBB, then this is
656 // 'water' that a constant pool island could be placed.
657 if (!BBHasFallthrough(&MBB))
658 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000659
Evan Chenga8e29892007-01-19 07:51:42 +0000660 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
661 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000662 if (I->isDebugValue())
663 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000664
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000665 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000666 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000667 bool isCond = false;
668 unsigned Bits = 0;
669 unsigned Scale = 1;
670 int UOpc = Opc;
671 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000672 default:
673 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000674 case ARM::t2BR_JT:
675 T2JumpTables.push_back(I);
676 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000677 case ARM::Bcc:
678 isCond = true;
679 UOpc = ARM::B;
680 // Fallthrough
681 case ARM::B:
682 Bits = 24;
683 Scale = 4;
684 break;
685 case ARM::tBcc:
686 isCond = true;
687 UOpc = ARM::tB;
688 Bits = 8;
689 Scale = 2;
690 break;
691 case ARM::tB:
692 Bits = 11;
693 Scale = 2;
694 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000695 case ARM::t2Bcc:
696 isCond = true;
697 UOpc = ARM::t2B;
698 Bits = 20;
699 Scale = 2;
700 break;
701 case ARM::t2B:
702 Bits = 24;
703 Scale = 2;
704 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000705 }
Evan Chengb43216e2007-02-01 10:16:15 +0000706
707 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000708 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000709 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000710 }
711
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000712 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
713 PushPopMIs.push_back(I);
714
Evan Chengd3d9d662009-07-23 18:27:47 +0000715 if (Opc == ARM::CONSTPOOL_ENTRY)
716 continue;
717
Evan Chenga8e29892007-01-19 07:51:42 +0000718 // Scan the instructions for constant pool operands.
719 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000720 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000721 // We found one. The addressing mode tells us the max displacement
722 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000723
Evan Chenga8e29892007-01-19 07:51:42 +0000724 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000725 unsigned Bits = 0;
726 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000727 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000728 bool IsSoImm = false;
729
730 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000731 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000732 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000733
734 // Taking the address of a CP entry.
735 case ARM::LEApcrel:
736 // This takes a SoImm, which is 8 bit immediate rotated. We'll
737 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000738 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000739 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000740 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000741 Scale = 4;
742 NegOk = true;
743 IsSoImm = true;
744 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000745 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000746 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000747 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000748 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000749 case ARM::tLEApcrel:
750 Bits = 8;
751 Scale = 4;
752 break;
753
Jim Grosbach3e556122010-10-26 22:37:02 +0000754 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000755 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000756 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000757 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000758 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000759 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000760
761 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000762 Bits = 8;
763 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000764 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000765
Jim Grosbache5165492009-11-09 00:11:35 +0000766 case ARM::VLDRD:
767 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000768 Bits = 8;
769 Scale = 4; // +-(offset_8*4)
770 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000771 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000772 }
Evan Chengb43216e2007-02-01 10:16:15 +0000773
Evan Chenga8e29892007-01-19 07:51:42 +0000774 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000775 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000776 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000777 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000778 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000779
780 // Increment corresponding CPEntry reference count.
781 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
782 assert(CPE && "Cannot find a corresponding CPEntry!");
783 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000784
Evan Chenga8e29892007-01-19 07:51:42 +0000785 // Instructions can only use one CP entry, don't bother scanning the
786 // rest of the operands.
787 break;
788 }
789 }
Evan Chenga8e29892007-01-19 07:51:42 +0000790 }
791}
792
Jim Grosbach7a465252012-03-23 23:07:03 +0000793/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000794/// This function updates BBInfo directly.
Jim Grosbach7a465252012-03-23 23:07:03 +0000795void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000796 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
797 BBI.Size = 0;
798 BBI.Unalign = 0;
799 BBI.PostAlign = 0;
800
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000801 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
802 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000803 BBI.Size += TII->GetInstSizeInBytes(I);
804 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
805 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000806 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000807 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000808 // Also consider instructions that may be shrunk later.
809 else if (isThumb && mayOptimizeThumb2Instruction(I))
810 BBI.Unalign = 1;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000811 }
812
813 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000814 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000815 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000816 MBB->getParent()->EnsureAlignment(2);
817 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000818}
819
Jim Grosbach7a465252012-03-23 23:07:03 +0000820/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Chenga8e29892007-01-19 07:51:42 +0000821/// from the start of the function. This offset changes as stuff is moved
822/// around inside the function.
Jim Grosbach7a465252012-03-23 23:07:03 +0000823unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Chenga8e29892007-01-19 07:51:42 +0000824 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000825
Evan Chenga8e29892007-01-19 07:51:42 +0000826 // The offset is composed of two things: the sum of the sizes of all MBB's
827 // before this instruction's block, and the offset from the start of the block
828 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000829 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000830
831 // Sum instructions before MI in MBB.
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000832 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Chenga8e29892007-01-19 07:51:42 +0000833 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000834 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000835 }
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000836 return Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000837}
838
839/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
840/// ID.
841static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
842 const MachineBasicBlock *RHS) {
843 return LHS->getNumber() < RHS->getNumber();
844}
845
Jim Grosbach7a465252012-03-23 23:07:03 +0000846/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Chenga8e29892007-01-19 07:51:42 +0000847/// machine function, it upsets all of the block numbers. Renumber the blocks
848/// and update the arrays that parallel this numbering.
Jim Grosbach7a465252012-03-23 23:07:03 +0000849void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000850 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000851 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000852
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000853 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000854 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000855 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000856
857 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000858 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000859 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000860 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
861 CompareMBBNumbers);
862 WaterList.insert(IP, NewBB);
863}
864
865
866/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000867/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000868/// account for this change and returns the newly created block.
Jim Grosbach7a465252012-03-23 23:07:03 +0000869MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000870 MachineBasicBlock *OrigBB = MI->getParent();
871
872 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000873 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000874 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000875 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000876 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000877
Evan Chenga8e29892007-01-19 07:51:42 +0000878 // Splice the instructions starting with MI over to NewBB.
879 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000880
Evan Chenga8e29892007-01-19 07:51:42 +0000881 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000882 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000883 // There doesn't seem to be meaningful DebugInfo available; this doesn't
884 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000885 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000886 if (!isThumb)
887 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
888 else
889 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
890 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000891 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000892
Evan Chenga8e29892007-01-19 07:51:42 +0000893 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000894 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000895
Evan Chenga8e29892007-01-19 07:51:42 +0000896 // OrigBB branches to NewBB.
897 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000898
Evan Chenga8e29892007-01-19 07:51:42 +0000899 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +0000900 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000902 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000903
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000904 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000905 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000906 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000907
Bob Wilson84945262009-05-12 17:09:30 +0000908 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000909 // available water after it (but not if it's already there, which happens
910 // when splitting before a conditional branch that is followed by an
911 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000912 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000913 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
914 CompareMBBNumbers);
915 MachineBasicBlock* WaterBB = *IP;
916 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000917 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000918 else
919 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000920 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000921
Dale Johannesen8086d582010-07-23 22:50:23 +0000922 // Figure out how large the OrigBB is. As the first half of the original
923 // block, it cannot contain a tablejump. The size includes
924 // the new jump we added. (It should be possible to do this without
925 // recounting everything, but it's very confusing, and this is rarely
926 // executed.)
Jim Grosbach7a465252012-03-23 23:07:03 +0000927 computeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000928
Dale Johannesen8086d582010-07-23 22:50:23 +0000929 // Figure out how large the NewMBB is. As the second half of the original
930 // block, it may contain a tablejump.
Jim Grosbach7a465252012-03-23 23:07:03 +0000931 computeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000932
Dale Johannesen99c49a42007-02-25 00:47:03 +0000933 // All BBOffsets following these blocks must be modified.
Jim Grosbach7a465252012-03-23 23:07:03 +0000934 adjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000935
936 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000937}
938
Jim Grosbach7a465252012-03-23 23:07:03 +0000939/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000940/// displacement computation. Update U.KnownAlignment to match its current
941/// basic block location.
Jim Grosbach7a465252012-03-23 23:07:03 +0000942unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
943 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000944 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
945 unsigned KnownBits = BBI.internalKnownBits();
946
947 // The value read from PC is offset from the actual instruction address.
948 UserOffset += (isThumb ? 4 : 8);
949
950 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
951 // Make sure U.getMaxDisp() returns a constrained range.
952 U.KnownAlignment = (KnownBits >= 2);
953
954 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
955 // purposes of the displacement computation; compensate for that here.
956 // For unknown alignments, getMaxDisp() constrains the range instead.
957 if (isThumb && U.KnownAlignment)
958 UserOffset &= ~3u;
959
960 return UserOffset;
961}
962
Jim Grosbach7a465252012-03-23 23:07:03 +0000963/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000964/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000965/// constant pool entry).
Jim Grosbach7a465252012-03-23 23:07:03 +0000966/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000967/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
968/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach7a465252012-03-23 23:07:03 +0000969bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000970 unsigned TrialOffset, unsigned MaxDisp,
971 bool NegativeOK, bool IsSoImm) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000972 if (UserOffset <= TrialOffset) {
973 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000974 if (TrialOffset - UserOffset <= MaxDisp)
975 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000976 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000977 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000978 if (UserOffset - TrialOffset <= MaxDisp)
979 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000980 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000981 }
982 return false;
983}
984
Jim Grosbach7a465252012-03-23 23:07:03 +0000985/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000986/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000987///
988/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach7a465252012-03-23 23:07:03 +0000989bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000990 MachineBasicBlock* Water, CPUser &U,
991 unsigned &Growth) {
992 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
993 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
994 unsigned NextBlockOffset, NextBlockAlignment;
995 MachineFunction::const_iterator NextBlock = Water;
996 if (++NextBlock == MF->end()) {
997 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
998 NextBlockAlignment = 0;
999 } else {
1000 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1001 NextBlockAlignment = NextBlock->getAlignment();
1002 }
1003 unsigned Size = U.CPEMI->getOperand(2).getImm();
1004 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001005
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001006 // The CPE may be able to hide in the alignment padding before the next
1007 // block. It may also cause more padding to be required if it is more aligned
1008 // that the next block.
1009 if (CPEEnd > NextBlockOffset) {
1010 Growth = CPEEnd - NextBlockOffset;
1011 // Compute the padding that would go at the end of the CPE to align the next
1012 // block.
1013 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1014
1015 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach7a465252012-03-23 23:07:03 +00001016 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001017 // in blocks between CPE and the user.
1018 if (CPEOffset < UserOffset)
1019 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1020 } else
1021 // CPE fits in existing padding.
1022 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001023
Jim Grosbach7a465252012-03-23 23:07:03 +00001024 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001025}
1026
Jim Grosbach7a465252012-03-23 23:07:03 +00001027/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001028/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001029bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001030 MachineInstr *CPEMI, unsigned MaxDisp,
1031 bool NegOk, bool DoDump) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001032 unsigned CPEOffset = getOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +00001033 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +00001034
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001035 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001036 DEBUG({
1037 unsigned Block = MI->getParent()->getNumber();
1038 const BasicBlockInfo &BBI = BBInfo[Block];
1039 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1040 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001041 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001042 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001043 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1044 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1045 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001046 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001047 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001048
Jim Grosbach7a465252012-03-23 23:07:03 +00001049 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001050}
1051
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001052#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001053/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1054/// unconditionally branches to its only successor.
1055static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1056 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1057 return false;
1058
1059 MachineBasicBlock *Succ = *MBB->succ_begin();
1060 MachineBasicBlock *Pred = *MBB->pred_begin();
1061 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001062 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1063 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001064 return PredMI->getOperand(0).getMBB() == Succ;
1065 return false;
1066}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001067#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001068
Jim Grosbach7a465252012-03-23 23:07:03 +00001069void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001070 unsigned BBNum = BB->getNumber();
1071 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001072 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001073 // Include the alignment of the current block.
1074 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1075 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1076 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001077
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001078 // This is where block i begins. Stop if the offset is already correct,
1079 // and we have updated 2 blocks. This is the maximum number of blocks
1080 // changed before calling this function.
1081 if (i > BBNum + 2 &&
1082 BBInfo[i].Offset == Offset &&
1083 BBInfo[i].KnownBits == KnownBits)
1084 break;
1085
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001086 BBInfo[i].Offset = Offset;
1087 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001088 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001089}
1090
Jim Grosbach7a465252012-03-23 23:07:03 +00001091/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001092/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001093/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001094/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001095
Jim Grosbach7a465252012-03-23 23:07:03 +00001096bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1097 MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001098 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001099 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1100 assert(CPE && "Unexpected!");
1101 if (--CPE->RefCount == 0) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001102 removeDeadCPEMI(CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001103 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001104 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001105 return true;
1106 }
1107 return false;
1108}
1109
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001110/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1111/// if not, see if an in-range clone of the CPE is in range, and if so,
1112/// change the data structures so the user references the clone. Returns:
1113/// 0 = no existing entry found
1114/// 1 = entry found, and there were no code insertions or deletions
1115/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach7a465252012-03-23 23:07:03 +00001116int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001117{
1118 MachineInstr *UserMI = U.MI;
1119 MachineInstr *CPEMI = U.CPEMI;
1120
1121 // Check to see if the CPE is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001122 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1123 true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001124 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001125 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001126 }
1127
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001128 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001129 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001130 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1131 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1132 // We already tried this one
1133 if (CPEs[i].CPEMI == CPEMI)
1134 continue;
1135 // Removing CPEs can leave empty entries, skip
1136 if (CPEs[i].CPEMI == NULL)
1137 continue;
Jim Grosbach7a465252012-03-23 23:07:03 +00001138 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001139 U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001140 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001141 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001142 // Point the CPUser node to the replacement
1143 U.CPEMI = CPEs[i].CPEMI;
1144 // Change the CPI in the instruction operand to refer to the clone.
1145 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001146 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001147 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001148 break;
1149 }
1150 // Adjust the refcount of the clone...
1151 CPEs[i].RefCount++;
1152 // ...and the original. If we didn't remove the old entry, none of the
1153 // addresses changed, so we don't need another pass.
Jim Grosbach7a465252012-03-23 23:07:03 +00001154 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001155 }
1156 }
1157 return 0;
1158}
1159
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001160/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1161/// the specific unconditional branch instruction.
1162static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001163 switch (Opc) {
1164 case ARM::tB:
1165 return ((1<<10)-1)*2;
1166 case ARM::t2B:
1167 return ((1<<23)-1)*2;
1168 default:
1169 break;
1170 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001171
David Goodwin5e47a9a2009-06-30 18:04:13 +00001172 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001173}
1174
Jim Grosbach7a465252012-03-23 23:07:03 +00001175/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001176/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001177/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001178/// is set to the WaterList entry. For Thumb, prefer water that will not
1179/// introduce padding to water that will. To ensure that this pass
1180/// terminates, the CPE location for a particular CPUser is only allowed to
1181/// move to a lower address, so search backward from the end of the list and
1182/// prefer the first water that is in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001183bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001184 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001185 if (WaterList.empty())
1186 return false;
1187
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001188 unsigned BestGrowth = ~0u;
1189 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1190 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001191 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001192 // Check if water is in range and is either at a lower address than the
1193 // current "high water mark" or a new water block that was created since
1194 // the previous iteration by inserting an unconditional branch. In the
1195 // latter case, we want to allow resetting the high water mark back to
1196 // this new water since we haven't seen it before. Inserting branches
1197 // should be relatively uncommon and when it does happen, we want to be
1198 // sure to take advantage of it for all the CPEs near that block, so that
1199 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001200 unsigned Growth;
Jim Grosbach7a465252012-03-23 23:07:03 +00001201 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001202 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001203 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1204 // This is the least amount of required padding seen so far.
1205 BestGrowth = Growth;
1206 WaterIter = IP;
1207 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1208 << " Growth=" << Growth << '\n');
1209
1210 // Keep looking unless it is perfect.
1211 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001212 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001213 }
Bob Wilson3b757352009-10-12 19:04:03 +00001214 if (IP == B)
1215 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001216 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001217 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001218}
1219
Jim Grosbach7a465252012-03-23 23:07:03 +00001220/// createNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001221/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1222/// block is used if in range, and the conditional branch munged so control
1223/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001224/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001225/// block following which the new island can be inserted (the WaterList
1226/// is not adjusted).
Jim Grosbach7a465252012-03-23 23:07:03 +00001227void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001228 unsigned UserOffset,
1229 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001230 CPUser &U = CPUsers[CPUserIndex];
1231 MachineInstr *UserMI = U.MI;
1232 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001233 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001234 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001235 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001236
Bob Wilson36fa5322009-10-15 05:10:36 +00001237 // If the block does not end in an unconditional branch already, and if the
1238 // end of the block is within range, make new water there. (The addition
1239 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001240 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001241 if (BBHasFallthrough(UserMBB)) {
1242 // Size of branch to insert.
1243 unsigned Delta = isThumb1 ? 2 : 4;
1244 // End of UserBlock after adding a branch.
1245 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1246 // Compute the offset where the CPE will begin.
1247 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1248 UserBBI.postKnownBits());
Dale Johannesen8593e412007-04-29 19:19:30 +00001249
Jim Grosbach7a465252012-03-23 23:07:03 +00001250 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001251 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1252 << format(", expected CPE offset %#x\n", CPEOffset));
1253 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1254 // Add an unconditional branch from UserMBB to fallthrough block. Record
1255 // it for branch lengthening; this new branch will not get out of range,
1256 // but if the preceding conditional branch is out of range, the targets
1257 // will be exchanged, and the altered branch may be out of range, so the
1258 // machinery has to know about it.
1259 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1260 if (!isThumb)
1261 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1262 else
1263 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1264 .addImm(ARMCC::AL).addReg(0);
1265 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1266 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1267 MaxDisp, false, UncondBr));
1268 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001269 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001270 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001271 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001272 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001273
1274 // What a big block. Find a place within the block to split it. This is a
1275 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1276 // entries are 4 bytes: if instruction I references island CPE, and
1277 // instruction I+1 references CPE', it will not work well to put CPE as far
1278 // forward as possible, since then CPE' cannot immediately follow it (that
1279 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1280 // need to create a new island. So, we make a first guess, then walk through
1281 // the instructions between the one currently being looked at and the
1282 // possible insertion point, and make sure any other instructions that
1283 // reference CPEs will be able to use the same island area; if not, we back
1284 // up the insertion point.
1285
1286 // Try to split the block so it's fully aligned. Compute the latest split
1287 // point where we can add a 4-byte branch instruction, and then
1288 // WorstCaseAlign to LogAlign.
1289 unsigned LogAlign = MF->getAlignment();
1290 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1291 unsigned KnownBits = UserBBI.internalKnownBits();
1292 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001293 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001294 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1295 BaseInsertOffset));
1296
1297 // Account for alignment and unknown padding.
1298 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1299 BaseInsertOffset -= UPad;
1300
1301 // The 4 in the following is for the unconditional branch we'll be inserting
1302 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach7a465252012-03-23 23:07:03 +00001303 // inside isOffsetInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001304 BaseInsertOffset -= 4;
1305
1306 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1307 << " la=" << LogAlign
1308 << " kb=" << KnownBits
1309 << " up=" << UPad << '\n');
1310
1311 // This could point off the end of the block if we've already got constant
1312 // pool entries following this block; only the last one is in the water list.
1313 // Back past any possible branches (allow for a conditional and a maximally
1314 // long unconditional).
1315 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1316 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1317 (isThumb1 ? 6 : 8);
1318 unsigned EndInsertOffset =
1319 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1320 CPEMI->getOperand(2).getImm();
1321 MachineBasicBlock::iterator MI = UserMI;
1322 ++MI;
1323 unsigned CPUIndex = CPUserIndex+1;
1324 unsigned NumCPUsers = CPUsers.size();
1325 MachineInstr *LastIT = 0;
1326 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1327 Offset < BaseInsertOffset;
1328 Offset += TII->GetInstSizeInBytes(MI),
1329 MI = llvm::next(MI)) {
1330 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1331 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach7a465252012-03-23 23:07:03 +00001332 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001333 // Shift intertion point by one unit of alignment so it is within reach.
1334 BaseInsertOffset -= 1u << LogAlign;
1335 EndInsertOffset -= 1u << LogAlign;
1336 }
1337 // This is overly conservative, as we don't account for CPEMIs being
1338 // reused within the block, but it doesn't matter much. Also assume CPEs
1339 // are added in order with alignment padding. We may eventually be able
1340 // to pack the aligned CPEs better.
1341 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1342 1u << getCPELogAlign(U.CPEMI)) +
1343 U.CPEMI->getOperand(2).getImm();
1344 CPUIndex++;
1345 }
1346
1347 // Remember the last IT instruction.
1348 if (MI->getOpcode() == ARM::t2IT)
1349 LastIT = MI;
1350 }
1351
1352 --MI;
1353
1354 // Avoid splitting an IT block.
1355 if (LastIT) {
1356 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001357 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001358 if (CC != ARMCC::AL)
1359 MI = LastIT;
1360 }
Jim Grosbach7a465252012-03-23 23:07:03 +00001361 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001362}
1363
Jim Grosbach7a465252012-03-23 23:07:03 +00001364/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001365/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001366/// place in-range. Return true if we changed any addresses (thus must run
1367/// another pass of branch lengthening), false otherwise.
Jim Grosbach7a465252012-03-23 23:07:03 +00001368bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001369 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001370 MachineInstr *UserMI = U.MI;
1371 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001372 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001374 // Compute this only once, it's expensive.
Jim Grosbach7a465252012-03-23 23:07:03 +00001375 unsigned UserOffset = getUserOffset(U);
Evan Cheng768c9f72007-04-27 08:14:15 +00001376
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001377 // See if the current entry is within range, or there is a clone of it
1378 // in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001379 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001380 if (result==1) return false;
1381 else if (result==2) return true;
1382
1383 // No existing clone of this CPE is within range.
1384 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001385 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001386
Bob Wilsonf98032e2009-10-12 21:23:15 +00001387 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001388 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001389 MachineBasicBlock *NewMBB;
1390 water_iterator IP;
Jim Grosbach7a465252012-03-23 23:07:03 +00001391 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001392 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001393 MachineBasicBlock *WaterBB = *IP;
1394
1395 // If the original WaterList entry was "new water" on this iteration,
1396 // propagate that to the new island. This is just keeping NewWaterList
1397 // updated to match the WaterList, which will be updated below.
1398 if (NewWaterList.count(WaterBB)) {
1399 NewWaterList.erase(WaterBB);
1400 NewWaterList.insert(NewIsland);
1401 }
1402 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001403 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001404
1405 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001406 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001407 DEBUG(dbgs() << "No water found\n");
Jim Grosbach7a465252012-03-23 23:07:03 +00001408 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001409
Jim Grosbach7a465252012-03-23 23:07:03 +00001410 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilsonb9239532009-10-15 20:49:47 +00001411 // called while handling branches so that the water will be seen on the
1412 // next iteration for constant pools, but in this context, we don't want
1413 // it. Check for this so it will be removed from the WaterList.
1414 // Also remove any entry from NewWaterList.
1415 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1416 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1417 if (IP != WaterList.end())
1418 NewWaterList.erase(WaterBB);
1419
1420 // We are adding new water. Update NewWaterList.
1421 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001422 }
1423
Bob Wilsonb9239532009-10-15 20:49:47 +00001424 // Remove the original WaterList entry; we want subsequent insertions in
1425 // this vicinity to go after the one we're about to insert. This
1426 // considerably reduces the number of times we have to move the same CPE
1427 // more than once and is also important to ensure the algorithm terminates.
1428 if (IP != WaterList.end())
1429 WaterList.erase(IP);
1430
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001431 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001432 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001433
1434 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +00001435 updateForInsertedWaterBlock(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001436
1437 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach7a465252012-03-23 23:07:03 +00001438 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001439
1440 // Now that we have an island to add the CPE to, clone the original CPE and
1441 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001442 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001443 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001444 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001445 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001446 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001447
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001448 // Mark the basic block as aligned as required by the const-pool entry.
1449 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001450
Evan Chenga8e29892007-01-19 07:51:42 +00001451 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001452 BBInfo[NewIsland->getNumber()].Size += Size;
Jim Grosbach7a465252012-03-23 23:07:03 +00001453 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001454
Evan Chenga8e29892007-01-19 07:51:42 +00001455 // Finally, change the CPI in the instruction operand to be ID.
1456 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001457 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001458 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001459 break;
1460 }
Bob Wilson84945262009-05-12 17:09:30 +00001461
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001462 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001463 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001464
Evan Chenga8e29892007-01-19 07:51:42 +00001465 return true;
1466}
1467
Jim Grosbach7a465252012-03-23 23:07:03 +00001468/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Chenged884f32007-04-03 23:39:48 +00001469/// sizes and offsets of impacted basic blocks.
Jim Grosbach7a465252012-03-23 23:07:03 +00001470void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Chenged884f32007-04-03 23:39:48 +00001471 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001472 unsigned Size = CPEMI->getOperand(2).getImm();
1473 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001474 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001475 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001476 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001477 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001478
1479 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1480 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001481 } else
1482 // Entries are sorted by descending alignment, so realign from the front.
1483 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1484
Jim Grosbach7a465252012-03-23 23:07:03 +00001485 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001486 // An island has only one predecessor BB and one successor BB. Check if
1487 // this BB's predecessor jumps directly to this BB's successor. This
1488 // shouldn't happen currently.
1489 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1490 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001491}
1492
Jim Grosbach7a465252012-03-23 23:07:03 +00001493/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Chenged884f32007-04-03 23:39:48 +00001494/// are zero.
Jim Grosbach7a465252012-03-23 23:07:03 +00001495bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Chenged884f32007-04-03 23:39:48 +00001496 unsigned MadeChange = false;
1497 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1498 std::vector<CPEntry> &CPEs = CPEntries[i];
1499 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1500 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001501 removeDeadCPEMI(CPEs[j].CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001502 CPEs[j].CPEMI = NULL;
1503 MadeChange = true;
1504 }
1505 }
Bob Wilson84945262009-05-12 17:09:30 +00001506 }
Evan Chenged884f32007-04-03 23:39:48 +00001507 return MadeChange;
1508}
1509
Jim Grosbach7a465252012-03-23 23:07:03 +00001510/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001511/// specific BB can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001512bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Chengc0dbec72007-01-31 19:57:44 +00001513 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001514 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach7a465252012-03-23 23:07:03 +00001515 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001516 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001517
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001518 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001519 << " from BB#" << MI->getParent()->getNumber()
1520 << " max delta=" << MaxDisp
Jim Grosbach7a465252012-03-23 23:07:03 +00001521 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattner705e07f2009-08-23 03:41:05 +00001522 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001523
Dale Johannesen8593e412007-04-29 19:19:30 +00001524 if (BrOffset <= DestOffset) {
1525 // Branch before the Dest.
1526 if (DestOffset-BrOffset <= MaxDisp)
1527 return true;
1528 } else {
1529 if (BrOffset-DestOffset <= MaxDisp)
1530 return true;
1531 }
1532 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001533}
1534
Jim Grosbach7a465252012-03-23 23:07:03 +00001535/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001536/// away to fit in its displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001537bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001538 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001539 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001540
Evan Chengc0dbec72007-01-31 19:57:44 +00001541 // Check to see if the DestBB is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001542 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001543 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001544
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001545 if (!Br.isCond)
Jim Grosbach7a465252012-03-23 23:07:03 +00001546 return fixupUnconditionalBr(Br);
1547 return fixupConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001548}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001549
Jim Grosbach7a465252012-03-23 23:07:03 +00001550/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001551/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001552/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001553/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001554bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001555ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001556 MachineInstr *MI = Br.MI;
1557 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001558 if (!isThumb1)
Jim Grosbach7a465252012-03-23 23:07:03 +00001559 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001560
1561 // Use BL to implement far jump.
1562 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001563 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001564 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001565 adjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001566 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001567 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001568
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001569 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001570
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001571 return true;
1572}
1573
Jim Grosbach7a465252012-03-23 23:07:03 +00001574/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001575/// far away to fit in its displacement field. It is converted to an inverse
1576/// conditional branch + an unconditional branch to the destination.
1577bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001578ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001579 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001580 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001581
Bob Wilson39bf0512009-05-12 17:35:29 +00001582 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001583 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001584 // blt L1
1585 // =>
1586 // bge L2
1587 // b L1
1588 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001589 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001590 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001591 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001592
1593 // If the branch is at the end of its MBB and that has a fall-through block,
1594 // direct the updated conditional branch to the fall-through block. Otherwise,
1595 // split the MBB before the next instruction.
1596 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001597 MachineInstr *BMI = &MBB->back();
1598 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001599
Dan Gohmanfe601042010-06-22 15:08:57 +00001600 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001601 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001602 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001603 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001604 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001605 // condition and swap destinations:
1606 // beq L1
1607 // b L2
1608 // =>
1609 // bne L2
1610 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001611 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001612 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001613 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001614 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001615 BMI->getOperand(0).setMBB(DestBB);
1616 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001617 MI->getOperand(1).setImm(CC);
1618 return true;
1619 }
1620 }
1621 }
1622
1623 if (NeedSplit) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001624 splitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001625 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001626 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001627 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001628 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001629 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001630 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001631 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001632 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001633
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001634 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001635 << " also invert condition and change dest. to BB#"
1636 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001637
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001638 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001639 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001640 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001641 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001642 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001643 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001644 if (isThumb)
1645 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1646 .addImm(ARMCC::AL).addReg(0);
1647 else
1648 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001649 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001650 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001651 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001652
1653 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001654 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001655 MI->eraseFromParent();
Jim Grosbach7a465252012-03-23 23:07:03 +00001656 adjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001657 return true;
1658}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001659
Jim Grosbach7a465252012-03-23 23:07:03 +00001660/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001661/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1662/// to do this if tBfar is not used.
Jim Grosbach7a465252012-03-23 23:07:03 +00001663bool ARMConstantIslands::undoLRSpillRestore() {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001664 bool MadeChange = false;
1665 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1666 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001667 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001668 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001669 MI->getOperand(2).getReg() == ARM::PC &&
1670 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001671 // Create the new insn and copy the predicate from the old.
1672 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1673 .addOperand(MI->getOperand(0))
1674 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001675 MI->eraseFromParent();
1676 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001677 }
1678 }
1679 return MadeChange;
1680}
Evan Cheng5657c012009-07-29 02:18:14 +00001681
Jim Grosbach7a465252012-03-23 23:07:03 +00001682// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001683// below may shrink MI.
1684bool
1685ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1686 switch(MI->getOpcode()) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001687 // optimizeThumb2Instructions.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001688 case ARM::t2LEApcrel:
1689 case ARM::t2LDRpci:
Jim Grosbach7a465252012-03-23 23:07:03 +00001690 // optimizeThumb2Branches.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001691 case ARM::t2B:
1692 case ARM::t2Bcc:
1693 case ARM::tBcc:
Jim Grosbach7a465252012-03-23 23:07:03 +00001694 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001695 case ARM::t2BR_JT:
1696 return true;
1697 }
1698 return false;
1699}
1700
Jim Grosbach7a465252012-03-23 23:07:03 +00001701bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001702 bool MadeChange = false;
1703
1704 // Shrink ADR and LDR from constantpool.
1705 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1706 CPUser &U = CPUsers[i];
1707 unsigned Opcode = U.MI->getOpcode();
1708 unsigned NewOpc = 0;
1709 unsigned Scale = 1;
1710 unsigned Bits = 0;
1711 switch (Opcode) {
1712 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001713 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLEApcrel;
1716 Bits = 8;
1717 Scale = 4;
1718 }
1719 break;
1720 case ARM::t2LDRpci:
1721 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1722 NewOpc = ARM::tLDRpci;
1723 Bits = 8;
1724 Scale = 4;
1725 }
1726 break;
1727 }
1728
1729 if (!NewOpc)
1730 continue;
1731
Jim Grosbach7a465252012-03-23 23:07:03 +00001732 unsigned UserOffset = getUserOffset(U);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001733 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001734
1735 // Be conservative with inline asm.
1736 if (!U.KnownAlignment)
1737 MaxOffs -= 2;
1738
Evan Chenga1efbbd2009-08-14 00:32:16 +00001739 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach7a465252012-03-23 23:07:03 +00001740 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001741 U.MI->setDesc(TII->get(NewOpc));
1742 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001743 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001744 adjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001745 ++NumT2CPShrunk;
1746 MadeChange = true;
1747 }
1748 }
1749
Jim Grosbach7a465252012-03-23 23:07:03 +00001750 MadeChange |= optimizeThumb2Branches();
1751 MadeChange |= optimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001752 return MadeChange;
1753}
1754
Jim Grosbach7a465252012-03-23 23:07:03 +00001755bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001756 bool MadeChange = false;
1757
1758 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1759 ImmBranch &Br = ImmBranches[i];
1760 unsigned Opcode = Br.MI->getOpcode();
1761 unsigned NewOpc = 0;
1762 unsigned Scale = 1;
1763 unsigned Bits = 0;
1764 switch (Opcode) {
1765 default: break;
1766 case ARM::t2B:
1767 NewOpc = ARM::tB;
1768 Bits = 11;
1769 Scale = 2;
1770 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001771 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001772 NewOpc = ARM::tBcc;
1773 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001774 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001775 break;
1776 }
Evan Chengde17fb62009-10-31 23:46:45 +00001777 }
1778 if (NewOpc) {
1779 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1780 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001781 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Evan Chengde17fb62009-10-31 23:46:45 +00001782 Br.MI->setDesc(TII->get(NewOpc));
1783 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001784 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001785 adjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001786 ++NumT2BrShrunk;
1787 MadeChange = true;
1788 }
1789 }
1790
1791 Opcode = Br.MI->getOpcode();
1792 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001793 continue;
1794
Evan Chengbfe8afa2012-01-14 01:53:46 +00001795 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1796 // so this transformation is not safe.
1797 if (!Br.MI->killsRegister(ARM::CPSR))
1798 continue;
1799
Evan Chengde17fb62009-10-31 23:46:45 +00001800 NewOpc = 0;
1801 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001802 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Chengde17fb62009-10-31 23:46:45 +00001803 if (Pred == ARMCC::EQ)
1804 NewOpc = ARM::tCBZ;
1805 else if (Pred == ARMCC::NE)
1806 NewOpc = ARM::tCBNZ;
1807 if (!NewOpc)
1808 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001809 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001810 // Check if the distance is within 126. Subtract starting offset by 2
1811 // because the cmp will be eliminated.
Jim Grosbach7a465252012-03-23 23:07:03 +00001812 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001813 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001814 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001815 MachineBasicBlock::iterator CmpMI = Br.MI;
1816 if (CmpMI != Br.MI->getParent()->begin()) {
1817 --CmpMI;
1818 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1819 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperc89c7442012-03-27 07:21:54 +00001820 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng0539c152011-04-01 22:09:28 +00001821 if (Pred == ARMCC::AL &&
1822 CmpMI->getOperand(1).getImm() == 0 &&
1823 isARMLowRegister(Reg)) {
1824 MachineBasicBlock *MBB = Br.MI->getParent();
1825 MachineInstr *NewBR =
1826 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1827 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1828 CmpMI->eraseFromParent();
1829 Br.MI->eraseFromParent();
1830 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001831 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001832 adjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001833 ++NumCBZ;
1834 MadeChange = true;
1835 }
Evan Chengde17fb62009-10-31 23:46:45 +00001836 }
1837 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001838 }
1839 }
1840
1841 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001842}
1843
Jim Grosbach7a465252012-03-23 23:07:03 +00001844/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chenga1efbbd2009-08-14 00:32:16 +00001845/// jumptables when it's possible.
Jim Grosbach7a465252012-03-23 23:07:03 +00001846bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001847 bool MadeChange = false;
1848
1849 // FIXME: After the tables are shrunk, can we get rid some of the
1850 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001851 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001852 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001853
Evan Cheng5657c012009-07-29 02:18:14 +00001854 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1855 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1856 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001857 const MCInstrDesc &MCID = MI->getDesc();
1858 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001859 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001860 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1861 unsigned JTI = JTOP.getIndex();
1862 assert(JTI < JT.size());
1863
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001864 bool ByteOk = true;
1865 bool HalfWordOk = true;
Jim Grosbach7a465252012-03-23 23:07:03 +00001866 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach80697d12009-11-12 17:25:07 +00001867 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001868 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1869 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001870 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001871 // Negative offset is not ok. FIXME: We should change BB layout to make
1872 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001873 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001874 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001875 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001876 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001877 HalfWordOk = false;
1878 if (!ByteOk && !HalfWordOk)
1879 break;
1880 }
1881
1882 if (ByteOk || HalfWordOk) {
1883 MachineBasicBlock *MBB = MI->getParent();
1884 unsigned BaseReg = MI->getOperand(0).getReg();
1885 bool BaseRegKill = MI->getOperand(0).isKill();
1886 if (!BaseRegKill)
1887 continue;
1888 unsigned IdxReg = MI->getOperand(1).getReg();
1889 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001890
1891 // Scan backwards to find the instruction that defines the base
1892 // register. Due to post-RA scheduling, we can't count on it
1893 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001894 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001895 MachineBasicBlock::iterator B = MBB->begin();
1896 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1897 --PrevI;
1898
1899 // If for some reason we didn't find it, we can't do anything, so
1900 // just skip this one.
1901 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001902 continue;
1903
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001904 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001905 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001906 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001907 // Make sure it only defines the base register and kills any uses
1908 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001909 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1910 const MachineOperand &MO = AddrMI->getOperand(k);
1911 if (!MO.isReg() || !MO.getReg())
1912 continue;
1913 if (MO.isDef() && MO.getReg() != BaseReg) {
1914 OptOk = false;
1915 break;
1916 }
1917 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1918 OptOk = false;
1919 break;
1920 }
1921 }
1922 if (!OptOk)
1923 continue;
1924
Owen Anderson6b8719f2010-12-13 22:51:08 +00001925 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001926 // that gave us the initial base register definition.
1927 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1928 ;
1929
Owen Anderson6b8719f2010-12-13 22:51:08 +00001930 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001931 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001932 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001933 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001934 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001935 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001936 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001937
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001938 if (!OptOk)
1939 continue;
1940
Jim Grosbachd092a872010-11-29 21:28:32 +00001941 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001942 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1943 .addReg(IdxReg, getKillRegState(IdxRegKill))
1944 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1945 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1946 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1947 // is 2-byte aligned. For now, asm printer will fix it up.
1948 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1949 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1950 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1951 OrigSize += TII->GetInstSizeInBytes(MI);
1952
1953 AddrMI->eraseFromParent();
1954 LeaMI->eraseFromParent();
1955 MI->eraseFromParent();
1956
1957 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001958 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001959 adjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001960
1961 ++NumTBs;
1962 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001963 }
1964 }
1965
1966 return MadeChange;
1967}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001968
Jim Grosbach7a465252012-03-23 23:07:03 +00001969/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach9249efe2009-11-16 18:55:47 +00001970/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach7a465252012-03-23 23:07:03 +00001971bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001972 bool MadeChange = false;
1973
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001974 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001975 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001976
Jim Grosbach80697d12009-11-12 17:25:07 +00001977 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1978 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1979 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001980 const MCInstrDesc &MCID = MI->getDesc();
1981 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001982 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001983 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1984 unsigned JTI = JTOP.getIndex();
1985 assert(JTI < JT.size());
1986
1987 // We prefer if target blocks for the jump table come after the jump
1988 // instruction so we can use TB[BH]. Loop through the target blocks
1989 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001990 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001991 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1992 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1993 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001994 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001995
Jim Grosbach08cbda52009-11-16 18:58:52 +00001996 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001997 // The destination precedes the switch. Try to move the block forward
1998 // so we have a positive offset.
1999 MachineBasicBlock *NewBB =
Jim Grosbach7a465252012-03-23 23:07:03 +00002000 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach80697d12009-11-12 17:25:07 +00002001 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002002 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00002003 MadeChange = true;
2004 }
2005 }
2006 }
2007
2008 return MadeChange;
2009}
2010
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002011MachineBasicBlock *ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +00002012adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach03e2d442010-07-07 22:53:35 +00002013 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00002014 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00002015 // table that branches back to the actual target. This is a very simple
2016 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00002017 MachineBasicBlock *TBB = 0, *FBB = 0;
2018 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002019 SmallVector<MachineOperand, 4> CondPrior;
2020 MachineFunction::iterator BBi = BB;
2021 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002022
Jim Grosbachca215e72009-11-16 17:10:56 +00002023 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002024 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00002025
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002026 // If the block ends in an unconditional branch, move it. The prior block
2027 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00002028 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002029 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002030 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002031 BB->moveAfter(JTBB);
2032 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002033 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00002034 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002035 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00002036 ++NumJTMoved;
2037 return NULL;
2038 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002039
2040 // Create a new MBB for the code after the jump BB.
2041 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002042 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002043 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002044 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002045
2046 // Add an unconditional branch from NewBB to BB.
2047 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2048 // correspond directly to anything in the source.
2049 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00002050 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2051 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002052
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002053 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002054 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002055
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002056 // Update the CFG.
2057 NewBB->addSuccessor(BB);
2058 JTBB->removeSuccessor(BB);
2059 JTBB->addSuccessor(NewBB);
2060
Jim Grosbach80697d12009-11-12 17:25:07 +00002061 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002062 return NewBB;
2063}