blob: fc35c7cb02005e23dded23bb9fa117a76fcd9a02 [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"
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000029#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
Jakob Stoklund Olesenf5bb45f2011-12-16 16:07:41 +000055// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000056static cl::opt<bool>
Jakob Stoklund Olesenb6ff6ec2011-12-15 22:14:45 +000057AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000058 cl::desc("Align constant islands in code"));
59
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000060/// UnknownPadding - Return the worst case padding that could result from
61/// unknown offset bits. This does not include alignment padding caused by
62/// known offset bits.
63///
64/// @param LogAlign log2(alignment)
65/// @param KnownBits Number of known low offset bits.
66static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67 if (KnownBits < LogAlign)
68 return (1u << LogAlign) - (1u << KnownBits);
69 return 0;
70}
71
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000072/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
73/// add padding such that:
74///
75/// 1. The result is aligned to 1 << LogAlign.
76///
77/// 2. No other value of the unknown bits would require more padding.
78///
79/// This may add more padding than is required to satisfy just one of the
80/// constraints. It is necessary to compute alignment this way to guarantee
81/// that we don't underestimate the padding before an aligned block. If the
82/// real padding before a block is larger than we think, constant pool entries
83/// may go out of range.
84static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
85 unsigned KnownBits) {
86 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000087 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000088
89 // Then align the result.
90 return RoundUpToAlignment(Offset, 1u << LogAlign);
91}
92
Evan Chenga8e29892007-01-19 07:51:42 +000093namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000094 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000095 /// requires constant pool entries to be scattered among the instructions
96 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000097 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000098 /// special instructions.
99 ///
100 /// The terminology used in this pass includes:
101 /// Islands - Clumps of constants placed in the function.
102 /// Water - Potential places where an island could be formed.
103 /// CPE - A constant pool entry that has been placed somewhere, which
104 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000106 /// BasicBlockInfo - Information about the offset and size of a single
107 /// basic block.
108 struct BasicBlockInfo {
109 /// Offset - Distance from the beginning of the function to the beginning
110 /// of this basic block.
111 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000112 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000113 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000114
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000115 /// Size - Size of the basic block in bytes. If the block contains
116 /// inline assembly, this is a worst case estimate.
117 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000118 /// The size does not include any alignment padding whether from the
119 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000120 unsigned Size;
121
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000122 /// KnownBits - The number of low bits in Offset that are known to be
123 /// exact. The remaining bits of Offset are an upper bound.
124 uint8_t KnownBits;
125
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000126 /// Unalign - When non-zero, the block contains instructions (inline asm)
127 /// of unknown size. The real size may be smaller than Size bytes by a
128 /// multiple of 1 << Unalign.
129 uint8_t Unalign;
130
131 /// PostAlign - When non-zero, the block terminator contains a .align
132 /// directive, so the end of the block is aligned to 1 << PostAlign
133 /// bytes.
134 uint8_t PostAlign;
135
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000136 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
137 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000138
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000139 /// Compute the number of known offset bits internally to this block.
140 /// This number should be used to predict worst case padding when
141 /// splitting the block.
142 unsigned internalKnownBits() const {
143 return Unalign ? Unalign : KnownBits;
144 }
145
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000146 /// Compute the offset immediately following this block. If LogAlign is
147 /// specified, return the offset the successor block will get if it has
148 /// this alignment.
149 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000150 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000151 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
152 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000153 return PO;
154 // Add alignment padding from the terminator.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000155 return WorstCaseAlign(PO, LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000156 }
157
158 /// Compute the number of known low bits of postOffset. If this block
159 /// contains inline asm, the number of known bits drops to the
160 /// instruction alignment. An aligned terminator may increase the number
161 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000162 /// If LogAlign is given, also consider the alignment of the next block.
163 unsigned postKnownBits(unsigned LogAlign = 0) const {
164 return std::max(std::max(unsigned(PostAlign), LogAlign),
165 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000166 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000167 };
168
169 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000170
Evan Chenga8e29892007-01-19 07:51:42 +0000171 /// WaterList - A sorted list of basic blocks where islands could be placed
172 /// (i.e. blocks that don't fall through to the following block, due
173 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000174 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000175
Bob Wilsonb9239532009-10-15 20:49:47 +0000176 /// NewWaterList - The subset of WaterList that was created since the
177 /// previous iteration by inserting unconditional branches.
178 SmallSet<MachineBasicBlock*, 4> NewWaterList;
179
Bob Wilson034de5f2009-10-12 18:52:13 +0000180 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
181
Evan Chenga8e29892007-01-19 07:51:42 +0000182 /// CPUser - One user of a constant pool, keeping the machine instruction
183 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000184 /// allowed from the instruction to the CP. The HighWaterMark records the
185 /// highest basic block where a new CPEntry can be placed. To ensure this
186 /// pass terminates, the CP entries are initially placed at the end of the
187 /// function and then move monotonically to lower addresses. The
188 /// exception to this rule is when the current CP entry for a particular
189 /// CPUser is out of range, but there is another CP entry for the same
190 /// constant value in range. We want to use the existing in-range CP
191 /// entry, but if it later moves out of range, the search for new water
192 /// should resume where it left off. The HighWaterMark is used to record
193 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000194 struct CPUser {
195 MachineInstr *MI;
196 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000197 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000198 private:
Evan Chenga8e29892007-01-19 07:51:42 +0000199 unsigned MaxDisp;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000200 public:
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000201 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000202 bool IsSoImm;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000203 bool KnownAlignment;
Evan Chengd3d9d662009-07-23 18:27:47 +0000204 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
205 bool neg, bool soimm)
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000206 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
207 KnownAlignment(false) {
Bob Wilson549dda92009-10-15 05:52:29 +0000208 HighWaterMark = CPEMI->getParent();
209 }
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000210 /// getMaxDisp - Returns the maximum displacement supported by MI.
211 /// Correct for unknown alignment.
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000212 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000213 unsigned getMaxDisp() const {
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000214 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000215 }
Evan Chenga8e29892007-01-19 07:51:42 +0000216 };
Bob Wilson84945262009-05-12 17:09:30 +0000217
Evan Chenga8e29892007-01-19 07:51:42 +0000218 /// CPUsers - Keep track of all of the machine instructions that use various
219 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000220 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000221
Evan Chengc99ef082007-02-09 20:54:44 +0000222 /// CPEntry - One per constant pool entry, keeping the machine instruction
223 /// pointer, the constpool index, and the number of CPUser's which
224 /// reference this entry.
225 struct CPEntry {
226 MachineInstr *CPEMI;
227 unsigned CPI;
228 unsigned RefCount;
229 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
230 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
231 };
232
233 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000234 /// instructions. For each original constpool index (i.e. those that
235 /// existed upon entry to this pass), it keeps a vector of entries.
236 /// Original elements are cloned as we go along; the clones are
237 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000238 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000239
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000240 /// ImmBranch - One per immediate branch, keeping the machine instruction
241 /// pointer, conditional or unconditional, the max displacement,
242 /// and (if isCond is true) the corresponding unconditional branch
243 /// opcode.
244 struct ImmBranch {
245 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000246 unsigned MaxDisp : 31;
247 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000248 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000249 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
250 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000251 };
252
Evan Cheng2706f972007-05-16 05:14:06 +0000253 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000254 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000255 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000256
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000257 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
258 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000259 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000260
Evan Cheng5657c012009-07-29 02:18:14 +0000261 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
262 SmallVector<MachineInstr*, 4> T2JumpTables;
263
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000264 /// HasFarJump - True if any far jump instruction has been emitted during
265 /// the branch fix up pass.
266 bool HasFarJump;
267
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000268 MachineFunction *MF;
269 MachineConstantPool *MCP;
Craig Topperacf20772012-03-25 23:49:58 +0000270 const ARMBaseInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000271 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000272 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000273 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000274 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000275 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000276 public:
Devang Patel19974732007-05-03 01:11:54 +0000277 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000278 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000279
Evan Cheng5657c012009-07-29 02:18:14 +0000280 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000281
282 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000283 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000284 }
Bob Wilson84945262009-05-12 17:09:30 +0000285
Evan Chenga8e29892007-01-19 07:51:42 +0000286 private:
Jim Grosbach7a465252012-03-23 23:07:03 +0000287 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000288 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000289 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach7a465252012-03-23 23:07:03 +0000290 void scanFunctionJumpTables();
291 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
292 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
293 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
294 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
295 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
296 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
297 bool findAvailableWater(CPUser&U, unsigned UserOffset,
298 water_iterator &WaterIter);
299 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000300 MachineBasicBlock *&NewMBB);
Jim Grosbach7a465252012-03-23 23:07:03 +0000301 bool handleConstantPoolUser(unsigned CPUserIndex);
302 void removeDeadCPEMI(MachineInstr *CPEMI);
303 bool removeUnusedCPEntries();
304 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
305 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
306 bool DoDump = false);
307 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000308 CPUser &U, unsigned &Growth);
Jim Grosbach7a465252012-03-23 23:07:03 +0000309 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
310 bool fixupImmediateBr(ImmBranch &Br);
311 bool fixupConditionalBr(ImmBranch &Br);
312 bool fixupUnconditionalBr(ImmBranch &Br);
313 bool undoLRSpillRestore();
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000314 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach7a465252012-03-23 23:07:03 +0000315 bool optimizeThumb2Instructions();
316 bool optimizeThumb2Branches();
317 bool reorderThumb2JumpTables();
318 bool optimizeThumb2JumpTables();
319 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000320 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000321
Jim Grosbach7a465252012-03-23 23:07:03 +0000322 void computeBlockSize(MachineBasicBlock *MBB);
323 unsigned getOffsetOf(MachineInstr *MI) const;
324 unsigned getUserOffset(CPUser&) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000325 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000326 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000327
Jim Grosbach7a465252012-03-23 23:07:03 +0000328 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000329 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach7a465252012-03-23 23:07:03 +0000330 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000331 const CPUser &U) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000332 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000333 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000334 }
Evan Chenga8e29892007-01-19 07:51:42 +0000335 };
Devang Patel19974732007-05-03 01:11:54 +0000336 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000337}
338
Dale Johannesen8593e412007-04-29 19:19:30 +0000339/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000340void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000341#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000342 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000343 MBBI != E; ++MBBI) {
344 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000345 unsigned Align = MBB->getAlignment();
346 unsigned MBBId = MBB->getNumber();
347 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
348 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000349 }
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000350 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000351 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
352 CPUser &U = CPUsers[i];
Jim Grosbach7a465252012-03-23 23:07:03 +0000353 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000354 // Verify offset using the real max displacement without the safety
355 // adjustment.
356 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000357 /* DoDump = */ true)) {
358 DEBUG(dbgs() << "OK\n");
359 continue;
360 }
361 DEBUG(dbgs() << "Out of range.\n");
362 dumpBBs();
363 DEBUG(MF->dump());
364 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000365 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000366#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000367}
368
369/// print block size and offset information - debugging
370void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000371 DEBUG({
372 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
373 const BasicBlockInfo &BBI = BBInfo[J];
374 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
375 << " kb=" << unsigned(BBI.KnownBits)
376 << " ua=" << unsigned(BBI.Unalign)
377 << " pa=" << unsigned(BBI.PostAlign)
378 << format(" size=%#x\n", BBInfo[J].Size);
379 }
380 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000381}
382
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000383/// createARMConstantIslandPass - returns an instance of the constpool
384/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000385FunctionPass *llvm::createARMConstantIslandPass() {
386 return new ARMConstantIslands();
387}
388
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000389bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
390 MF = &mf;
391 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000392
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000393 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000394 << MCP->getConstants().size() << " CP entries, aligned to "
395 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000396
Craig Topperacf20772012-03-25 23:49:58 +0000397 TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000398 AFI = MF->getInfo<ARMFunctionInfo>();
399 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000400
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000401 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000402 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000403 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000404
405 HasFarJump = false;
406
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +0000407 // This pass invalidates liveness information when it splits basic blocks.
408 MF->getRegInfo().invalidateLiveness();
409
Evan Chenga8e29892007-01-19 07:51:42 +0000410 // Renumber all of the machine basic blocks in the function, guaranteeing that
411 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000412 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000413
Jim Grosbach80697d12009-11-12 17:25:07 +0000414 // Try to reorder and otherwise adjust the block layout to make good use
415 // of the TB[BH] instructions.
416 bool MadeChange = false;
417 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000418 scanFunctionJumpTables();
419 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000420 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000421 T2JumpTables.clear();
422 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000423 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000424 }
425
Evan Chengd26b14c2009-07-31 18:28:05 +0000426 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000427 // This is so we can keep exact track of where the alignment padding goes.
428
Chris Lattner7d7dab02010-01-27 23:37:36 +0000429 // ARM and Thumb2 functions need to be 4-byte aligned.
430 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000431 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000432
Evan Chenga8e29892007-01-19 07:51:42 +0000433 // Perform the initial placement of the constant pool entries. To start with,
434 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000435 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000436 if (!MCP->isEmpty())
Jim Grosbach7a465252012-03-23 23:07:03 +0000437 doInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000438
Evan Chenga8e29892007-01-19 07:51:42 +0000439 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000440 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000441
Evan Chenga8e29892007-01-19 07:51:42 +0000442 // Do the initial scan of the function, building up information about the
443 // sizes of each block, the location of all the water, and finding all of the
444 // constant pool users.
Jim Grosbach7a465252012-03-23 23:07:03 +0000445 initializeFunctionInfo(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000446 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000447 DEBUG(dumpBBs());
448
Bob Wilson84945262009-05-12 17:09:30 +0000449
Evan Chenged884f32007-04-03 23:39:48 +0000450 /// Remove dead constant pool entries.
Jim Grosbach7a465252012-03-23 23:07:03 +0000451 MadeChange |= removeUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000452
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000453 // Iteratively place constant pool entries and fix up branches until there
454 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000455 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000456 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000457 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000458 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000459 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000460 CPChange |= handleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000461 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000462 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000463 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000464
Bob Wilsonb9239532009-10-15 20:49:47 +0000465 // Clear NewWaterList now. If we split a block for branches, it should
466 // appear as "new water" for the next iteration of constant pool placement.
467 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000468
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000469 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000470 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000471 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000472 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000473 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000474 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000475 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000476
477 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000478 break;
479 MadeChange = true;
480 }
Evan Chenged884f32007-04-03 23:39:48 +0000481
Evan Chenga1efbbd2009-08-14 00:32:16 +0000482 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000483 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach7a465252012-03-23 23:07:03 +0000484 MadeChange |= optimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000485
Dale Johannesen8593e412007-04-29 19:19:30 +0000486 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000487 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000488
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000489 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
490 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000491 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach7a465252012-03-23 23:07:03 +0000492 MadeChange |= undoLRSpillRestore();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000493
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000494 // Save the mapping between original and cloned constpool entries.
495 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
496 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
497 const CPEntry & CPE = CPEntries[i][j];
498 AFI->recordCPEClone(i, CPE.CPI);
499 }
500 }
501
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000502 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000503
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000504 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000505 WaterList.clear();
506 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000507 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000508 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000509 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000510 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000511
512 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000513}
514
Jim Grosbach7a465252012-03-23 23:07:03 +0000515/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Chenga8e29892007-01-19 07:51:42 +0000516/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000517void
Jim Grosbach7a465252012-03-23 23:07:03 +0000518ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000519 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000520 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
521 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000522
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000523 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000524 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000525
526 // Mark the basic block as required by the const-pool.
527 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
528 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
529
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000530 // The function needs to be as aligned as the basic blocks. The linker may
531 // move functions around based on their alignment.
532 MF->EnsureAlignment(BB->getAlignment());
533
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000534 // Order the entries in BB by descending alignment. That ensures correct
535 // alignment of all entries as long as BB is sufficiently aligned. Keep
536 // track of the insertion point for each alignment. We are going to bucket
537 // sort the entries as they are created.
538 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000539
Evan Chenga8e29892007-01-19 07:51:42 +0000540 // Add all of the constants from the constant pool to the end block, use an
541 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000542 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000543
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000544 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000545 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000546 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000547 assert(Size >= 4 && "Too small constant pool entry");
548 unsigned Align = CPs[i].getAlignment();
549 assert(isPowerOf2_32(Align) && "Invalid alignment");
550 // Verify that all constant pool entries are a multiple of their alignment.
551 // If not, we would have to pad them out so that instructions stay aligned.
552 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
553
554 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
555 unsigned LogAlign = Log2_32(Align);
556 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000557 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000558 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000559 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000560 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000561
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000562 // Ensure that future entries with higher alignment get inserted before
563 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000564 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000565 if (InsPoint[a] == InsAt)
566 InsPoint[a] = CPEMI;
567
Evan Chengc99ef082007-02-09 20:54:44 +0000568 // Add a new CPEntry, but no corresponding CPUser yet.
569 std::vector<CPEntry> CPEs;
570 CPEs.push_back(CPEntry(CPEMI, i));
571 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000572 ++NumCPEs;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000573 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
574 << Size << ", align = " << Align <<'\n');
Evan Chenga8e29892007-01-19 07:51:42 +0000575 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000576 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000577}
578
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000579/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000580/// into the block immediately after it.
581static bool BBHasFallthrough(MachineBasicBlock *MBB) {
582 // Get the next machine basic block in the function.
583 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000584 // Can't fall off end of function.
585 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000586 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000587
Chris Lattner7896c9f2009-12-03 00:50:42 +0000588 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000589 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
590 E = MBB->succ_end(); I != E; ++I)
591 if (*I == NextBB)
592 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000593
Evan Chenga8e29892007-01-19 07:51:42 +0000594 return false;
595}
596
Evan Chengc99ef082007-02-09 20:54:44 +0000597/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
598/// look up the corresponding CPEntry.
599ARMConstantIslands::CPEntry
600*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
601 const MachineInstr *CPEMI) {
602 std::vector<CPEntry> &CPEs = CPEntries[CPI];
603 // Number of entries per constpool index should be small, just do a
604 // linear search.
605 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
606 if (CPEs[i].CPEMI == CPEMI)
607 return &CPEs[i];
608 }
609 return NULL;
610}
611
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000612/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000613/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000614unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
615 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
616
617 // Everything is 4-byte aligned unless AlignConstantIslands is set.
618 if (!AlignConstantIslands)
619 return 2;
620
621 unsigned CPI = CPEMI->getOperand(1).getIndex();
622 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
623 unsigned Align = MCP->getConstants()[CPI].getAlignment();
624 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
625 return Log2_32(Align);
626}
627
Jim Grosbach7a465252012-03-23 23:07:03 +0000628/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach80697d12009-11-12 17:25:07 +0000629/// information about the sizes of each block and the locations of all
630/// the jump tables.
Jim Grosbach7a465252012-03-23 23:07:03 +0000631void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000632 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000633 MBBI != E; ++MBBI) {
634 MachineBasicBlock &MBB = *MBBI;
635
Jim Grosbach80697d12009-11-12 17:25:07 +0000636 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000637 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000638 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000639 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000640 }
641}
642
Jim Grosbach7a465252012-03-23 23:07:03 +0000643/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Chenga8e29892007-01-19 07:51:42 +0000644/// information about the sizes of each block, the location of all the water,
645/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000646void ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +0000647initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000648 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000649 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000650
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000651 // First thing, compute the size of all basic blocks, and see if the function
652 // has any inline assembly in it. If so, we have to be conservative about
653 // alignment assumptions, as we don't know for sure the size of any
654 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000655 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach7a465252012-03-23 23:07:03 +0000656 computeBlockSize(I);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000657
658 // The known bits of the entry block offset are determined by the function
659 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000660 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000661
662 // Compute block offsets and known bits.
Jim Grosbach7a465252012-03-23 23:07:03 +0000663 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000664
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000665 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000666 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000667 MBBI != E; ++MBBI) {
668 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000669
Evan Chenga8e29892007-01-19 07:51:42 +0000670 // If this block doesn't fall through into the next MBB, then this is
671 // 'water' that a constant pool island could be placed.
672 if (!BBHasFallthrough(&MBB))
673 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000674
Evan Chenga8e29892007-01-19 07:51:42 +0000675 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
676 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000677 if (I->isDebugValue())
678 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000679
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000680 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000681 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000682 bool isCond = false;
683 unsigned Bits = 0;
684 unsigned Scale = 1;
685 int UOpc = Opc;
686 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000687 default:
688 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000689 case ARM::t2BR_JT:
690 T2JumpTables.push_back(I);
691 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000692 case ARM::Bcc:
693 isCond = true;
694 UOpc = ARM::B;
695 // Fallthrough
696 case ARM::B:
697 Bits = 24;
698 Scale = 4;
699 break;
700 case ARM::tBcc:
701 isCond = true;
702 UOpc = ARM::tB;
703 Bits = 8;
704 Scale = 2;
705 break;
706 case ARM::tB:
707 Bits = 11;
708 Scale = 2;
709 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000710 case ARM::t2Bcc:
711 isCond = true;
712 UOpc = ARM::t2B;
713 Bits = 20;
714 Scale = 2;
715 break;
716 case ARM::t2B:
717 Bits = 24;
718 Scale = 2;
719 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000720 }
Evan Chengb43216e2007-02-01 10:16:15 +0000721
722 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000723 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000724 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000725 }
726
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000727 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
728 PushPopMIs.push_back(I);
729
Evan Chengd3d9d662009-07-23 18:27:47 +0000730 if (Opc == ARM::CONSTPOOL_ENTRY)
731 continue;
732
Evan Chenga8e29892007-01-19 07:51:42 +0000733 // Scan the instructions for constant pool operands.
734 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000735 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000736 // We found one. The addressing mode tells us the max displacement
737 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000738
Evan Chenga8e29892007-01-19 07:51:42 +0000739 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000740 unsigned Bits = 0;
741 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000742 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000743 bool IsSoImm = false;
744
745 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000746 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000747 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000748
749 // Taking the address of a CP entry.
750 case ARM::LEApcrel:
751 // This takes a SoImm, which is 8 bit immediate rotated. We'll
752 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000753 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000754 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000755 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000756 Scale = 4;
757 NegOk = true;
758 IsSoImm = true;
759 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000760 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000761 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000762 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000763 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000764 case ARM::tLEApcrel:
765 Bits = 8;
766 Scale = 4;
767 break;
768
Jim Grosbach3e556122010-10-26 22:37:02 +0000769 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000770 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000771 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000772 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000773 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000774 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000775
776 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000777 Bits = 8;
778 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000779 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000780
Jim Grosbache5165492009-11-09 00:11:35 +0000781 case ARM::VLDRD:
782 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000783 Bits = 8;
784 Scale = 4; // +-(offset_8*4)
785 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000786 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000787 }
Evan Chengb43216e2007-02-01 10:16:15 +0000788
Evan Chenga8e29892007-01-19 07:51:42 +0000789 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000790 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000791 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000792 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000793 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000794
795 // Increment corresponding CPEntry reference count.
796 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
797 assert(CPE && "Cannot find a corresponding CPEntry!");
798 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000799
Evan Chenga8e29892007-01-19 07:51:42 +0000800 // Instructions can only use one CP entry, don't bother scanning the
801 // rest of the operands.
802 break;
803 }
804 }
Evan Chenga8e29892007-01-19 07:51:42 +0000805 }
806}
807
Jim Grosbach7a465252012-03-23 23:07:03 +0000808/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000809/// This function updates BBInfo directly.
Jim Grosbach7a465252012-03-23 23:07:03 +0000810void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000811 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
812 BBI.Size = 0;
813 BBI.Unalign = 0;
814 BBI.PostAlign = 0;
815
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000816 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
817 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000818 BBI.Size += TII->GetInstSizeInBytes(I);
819 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
820 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000821 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000822 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000823 // Also consider instructions that may be shrunk later.
824 else if (isThumb && mayOptimizeThumb2Instruction(I))
825 BBI.Unalign = 1;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000826 }
827
828 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000829 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000830 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000831 MBB->getParent()->EnsureAlignment(2);
832 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000833}
834
Jim Grosbach7a465252012-03-23 23:07:03 +0000835/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Chenga8e29892007-01-19 07:51:42 +0000836/// from the start of the function. This offset changes as stuff is moved
837/// around inside the function.
Jim Grosbach7a465252012-03-23 23:07:03 +0000838unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Chenga8e29892007-01-19 07:51:42 +0000839 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000840
Evan Chenga8e29892007-01-19 07:51:42 +0000841 // The offset is composed of two things: the sum of the sizes of all MBB's
842 // before this instruction's block, and the offset from the start of the block
843 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000844 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000845
846 // Sum instructions before MI in MBB.
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000847 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Chenga8e29892007-01-19 07:51:42 +0000848 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000849 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000850 }
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000851 return Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000852}
853
854/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
855/// ID.
856static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
857 const MachineBasicBlock *RHS) {
858 return LHS->getNumber() < RHS->getNumber();
859}
860
Jim Grosbach7a465252012-03-23 23:07:03 +0000861/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Chenga8e29892007-01-19 07:51:42 +0000862/// machine function, it upsets all of the block numbers. Renumber the blocks
863/// and update the arrays that parallel this numbering.
Jim Grosbach7a465252012-03-23 23:07:03 +0000864void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000865 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000866 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000867
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000868 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000869 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000870 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000871
872 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000873 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000874 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000875 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
876 CompareMBBNumbers);
877 WaterList.insert(IP, NewBB);
878}
879
880
881/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000882/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000883/// account for this change and returns the newly created block.
Jim Grosbach7a465252012-03-23 23:07:03 +0000884MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000885 MachineBasicBlock *OrigBB = MI->getParent();
886
887 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000888 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000889 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000890 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000891 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000892
Evan Chenga8e29892007-01-19 07:51:42 +0000893 // Splice the instructions starting with MI over to NewBB.
894 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000895
Evan Chenga8e29892007-01-19 07:51:42 +0000896 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000897 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000898 // There doesn't seem to be meaningful DebugInfo available; this doesn't
899 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000900 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000901 if (!isThumb)
902 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
903 else
904 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
905 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000906 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000907
Evan Chenga8e29892007-01-19 07:51:42 +0000908 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000909 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000910
Evan Chenga8e29892007-01-19 07:51:42 +0000911 // OrigBB branches to NewBB.
912 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000913
Evan Chenga8e29892007-01-19 07:51:42 +0000914 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +0000915 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000916 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000917 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000918
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000919 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000920 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000921 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000922
Bob Wilson84945262009-05-12 17:09:30 +0000923 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000924 // available water after it (but not if it's already there, which happens
925 // when splitting before a conditional branch that is followed by an
926 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000927 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000928 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
929 CompareMBBNumbers);
930 MachineBasicBlock* WaterBB = *IP;
931 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000932 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000933 else
934 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000935 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000936
Dale Johannesen8086d582010-07-23 22:50:23 +0000937 // Figure out how large the OrigBB is. As the first half of the original
938 // block, it cannot contain a tablejump. The size includes
939 // the new jump we added. (It should be possible to do this without
940 // recounting everything, but it's very confusing, and this is rarely
941 // executed.)
Jim Grosbach7a465252012-03-23 23:07:03 +0000942 computeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000943
Dale Johannesen8086d582010-07-23 22:50:23 +0000944 // Figure out how large the NewMBB is. As the second half of the original
945 // block, it may contain a tablejump.
Jim Grosbach7a465252012-03-23 23:07:03 +0000946 computeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000947
Dale Johannesen99c49a42007-02-25 00:47:03 +0000948 // All BBOffsets following these blocks must be modified.
Jim Grosbach7a465252012-03-23 23:07:03 +0000949 adjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000950
951 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000952}
953
Jim Grosbach7a465252012-03-23 23:07:03 +0000954/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000955/// displacement computation. Update U.KnownAlignment to match its current
956/// basic block location.
Jim Grosbach7a465252012-03-23 23:07:03 +0000957unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
958 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000959 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
960 unsigned KnownBits = BBI.internalKnownBits();
961
962 // The value read from PC is offset from the actual instruction address.
963 UserOffset += (isThumb ? 4 : 8);
964
965 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
966 // Make sure U.getMaxDisp() returns a constrained range.
967 U.KnownAlignment = (KnownBits >= 2);
968
969 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
970 // purposes of the displacement computation; compensate for that here.
971 // For unknown alignments, getMaxDisp() constrains the range instead.
972 if (isThumb && U.KnownAlignment)
973 UserOffset &= ~3u;
974
975 return UserOffset;
976}
977
Jim Grosbach7a465252012-03-23 23:07:03 +0000978/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000979/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000980/// constant pool entry).
Jim Grosbach7a465252012-03-23 23:07:03 +0000981/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000982/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
983/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach7a465252012-03-23 23:07:03 +0000984bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000985 unsigned TrialOffset, unsigned MaxDisp,
986 bool NegativeOK, bool IsSoImm) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000987 if (UserOffset <= TrialOffset) {
988 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000989 if (TrialOffset - UserOffset <= MaxDisp)
990 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000991 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000992 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000993 if (UserOffset - TrialOffset <= MaxDisp)
994 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000995 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000996 }
997 return false;
998}
999
Jim Grosbach7a465252012-03-23 23:07:03 +00001000/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001001/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001002///
1003/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach7a465252012-03-23 23:07:03 +00001004bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001005 MachineBasicBlock* Water, CPUser &U,
1006 unsigned &Growth) {
1007 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1008 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1009 unsigned NextBlockOffset, NextBlockAlignment;
1010 MachineFunction::const_iterator NextBlock = Water;
1011 if (++NextBlock == MF->end()) {
1012 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1013 NextBlockAlignment = 0;
1014 } else {
1015 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1016 NextBlockAlignment = NextBlock->getAlignment();
1017 }
1018 unsigned Size = U.CPEMI->getOperand(2).getImm();
1019 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001020
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001021 // The CPE may be able to hide in the alignment padding before the next
1022 // block. It may also cause more padding to be required if it is more aligned
1023 // that the next block.
1024 if (CPEEnd > NextBlockOffset) {
1025 Growth = CPEEnd - NextBlockOffset;
1026 // Compute the padding that would go at the end of the CPE to align the next
1027 // block.
1028 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1029
1030 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach7a465252012-03-23 23:07:03 +00001031 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001032 // in blocks between CPE and the user.
1033 if (CPEOffset < UserOffset)
1034 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1035 } else
1036 // CPE fits in existing padding.
1037 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001038
Jim Grosbach7a465252012-03-23 23:07:03 +00001039 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001040}
1041
Jim Grosbach7a465252012-03-23 23:07:03 +00001042/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001043/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001044bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001045 MachineInstr *CPEMI, unsigned MaxDisp,
1046 bool NegOk, bool DoDump) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001047 unsigned CPEOffset = getOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +00001048 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +00001049
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001050 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001051 DEBUG({
1052 unsigned Block = MI->getParent()->getNumber();
1053 const BasicBlockInfo &BBI = BBInfo[Block];
1054 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1055 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001056 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001057 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001058 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1059 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1060 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001061 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001062 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001063
Jim Grosbach7a465252012-03-23 23:07:03 +00001064 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001065}
1066
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001067#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001068/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1069/// unconditionally branches to its only successor.
1070static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1071 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1072 return false;
1073
1074 MachineBasicBlock *Succ = *MBB->succ_begin();
1075 MachineBasicBlock *Pred = *MBB->pred_begin();
1076 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001077 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1078 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001079 return PredMI->getOperand(0).getMBB() == Succ;
1080 return false;
1081}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001082#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001083
Jim Grosbach7a465252012-03-23 23:07:03 +00001084void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001085 unsigned BBNum = BB->getNumber();
1086 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001087 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001088 // Include the alignment of the current block.
1089 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1090 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1091 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001092
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001093 // This is where block i begins. Stop if the offset is already correct,
1094 // and we have updated 2 blocks. This is the maximum number of blocks
1095 // changed before calling this function.
1096 if (i > BBNum + 2 &&
1097 BBInfo[i].Offset == Offset &&
1098 BBInfo[i].KnownBits == KnownBits)
1099 break;
1100
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001101 BBInfo[i].Offset = Offset;
1102 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001103 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001104}
1105
Jim Grosbach7a465252012-03-23 23:07:03 +00001106/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001107/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001108/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001109/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001110
Jim Grosbach7a465252012-03-23 23:07:03 +00001111bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1112 MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001113 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001114 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1115 assert(CPE && "Unexpected!");
1116 if (--CPE->RefCount == 0) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001117 removeDeadCPEMI(CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001118 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001119 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001120 return true;
1121 }
1122 return false;
1123}
1124
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001125/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1126/// if not, see if an in-range clone of the CPE is in range, and if so,
1127/// change the data structures so the user references the clone. Returns:
1128/// 0 = no existing entry found
1129/// 1 = entry found, and there were no code insertions or deletions
1130/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach7a465252012-03-23 23:07:03 +00001131int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001132{
1133 MachineInstr *UserMI = U.MI;
1134 MachineInstr *CPEMI = U.CPEMI;
1135
1136 // Check to see if the CPE is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001137 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1138 true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001139 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001140 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001141 }
1142
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001143 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001144 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001145 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1146 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1147 // We already tried this one
1148 if (CPEs[i].CPEMI == CPEMI)
1149 continue;
1150 // Removing CPEs can leave empty entries, skip
1151 if (CPEs[i].CPEMI == NULL)
1152 continue;
Jim Grosbach7a465252012-03-23 23:07:03 +00001153 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001154 U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001155 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001156 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001157 // Point the CPUser node to the replacement
1158 U.CPEMI = CPEs[i].CPEMI;
1159 // Change the CPI in the instruction operand to refer to the clone.
1160 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001161 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001162 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001163 break;
1164 }
1165 // Adjust the refcount of the clone...
1166 CPEs[i].RefCount++;
1167 // ...and the original. If we didn't remove the old entry, none of the
1168 // addresses changed, so we don't need another pass.
Jim Grosbach7a465252012-03-23 23:07:03 +00001169 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001170 }
1171 }
1172 return 0;
1173}
1174
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001175/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1176/// the specific unconditional branch instruction.
1177static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001178 switch (Opc) {
1179 case ARM::tB:
1180 return ((1<<10)-1)*2;
1181 case ARM::t2B:
1182 return ((1<<23)-1)*2;
1183 default:
1184 break;
1185 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001186
David Goodwin5e47a9a2009-06-30 18:04:13 +00001187 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001188}
1189
Jim Grosbach7a465252012-03-23 23:07:03 +00001190/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001191/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001192/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001193/// is set to the WaterList entry. For Thumb, prefer water that will not
1194/// introduce padding to water that will. To ensure that this pass
1195/// terminates, the CPE location for a particular CPUser is only allowed to
1196/// move to a lower address, so search backward from the end of the list and
1197/// prefer the first water that is in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001198bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001199 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001200 if (WaterList.empty())
1201 return false;
1202
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001203 unsigned BestGrowth = ~0u;
1204 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1205 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001206 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001207 // Check if water is in range and is either at a lower address than the
1208 // current "high water mark" or a new water block that was created since
1209 // the previous iteration by inserting an unconditional branch. In the
1210 // latter case, we want to allow resetting the high water mark back to
1211 // this new water since we haven't seen it before. Inserting branches
1212 // should be relatively uncommon and when it does happen, we want to be
1213 // sure to take advantage of it for all the CPEs near that block, so that
1214 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001215 unsigned Growth;
Jim Grosbach7a465252012-03-23 23:07:03 +00001216 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001217 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001218 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1219 // This is the least amount of required padding seen so far.
1220 BestGrowth = Growth;
1221 WaterIter = IP;
1222 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1223 << " Growth=" << Growth << '\n');
1224
1225 // Keep looking unless it is perfect.
1226 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001227 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001228 }
Bob Wilson3b757352009-10-12 19:04:03 +00001229 if (IP == B)
1230 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001231 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001232 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001233}
1234
Jim Grosbach7a465252012-03-23 23:07:03 +00001235/// createNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001236/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1237/// block is used if in range, and the conditional branch munged so control
1238/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001239/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001240/// block following which the new island can be inserted (the WaterList
1241/// is not adjusted).
Jim Grosbach7a465252012-03-23 23:07:03 +00001242void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001243 unsigned UserOffset,
1244 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001245 CPUser &U = CPUsers[CPUserIndex];
1246 MachineInstr *UserMI = U.MI;
1247 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001248 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001249 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001250 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001251
Bob Wilson36fa5322009-10-15 05:10:36 +00001252 // If the block does not end in an unconditional branch already, and if the
1253 // end of the block is within range, make new water there. (The addition
1254 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001255 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001256 if (BBHasFallthrough(UserMBB)) {
1257 // Size of branch to insert.
1258 unsigned Delta = isThumb1 ? 2 : 4;
1259 // End of UserBlock after adding a branch.
1260 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1261 // Compute the offset where the CPE will begin.
1262 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1263 UserBBI.postKnownBits());
Dale Johannesen8593e412007-04-29 19:19:30 +00001264
Jim Grosbach7a465252012-03-23 23:07:03 +00001265 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001266 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1267 << format(", expected CPE offset %#x\n", CPEOffset));
1268 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1269 // Add an unconditional branch from UserMBB to fallthrough block. Record
1270 // it for branch lengthening; this new branch will not get out of range,
1271 // but if the preceding conditional branch is out of range, the targets
1272 // will be exchanged, and the altered branch may be out of range, so the
1273 // machinery has to know about it.
1274 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1275 if (!isThumb)
1276 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1277 else
1278 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1279 .addImm(ARMCC::AL).addReg(0);
1280 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1281 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1282 MaxDisp, false, UncondBr));
1283 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001284 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001285 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001286 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001287 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001288
1289 // What a big block. Find a place within the block to split it. This is a
1290 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1291 // entries are 4 bytes: if instruction I references island CPE, and
1292 // instruction I+1 references CPE', it will not work well to put CPE as far
1293 // forward as possible, since then CPE' cannot immediately follow it (that
1294 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1295 // need to create a new island. So, we make a first guess, then walk through
1296 // the instructions between the one currently being looked at and the
1297 // possible insertion point, and make sure any other instructions that
1298 // reference CPEs will be able to use the same island area; if not, we back
1299 // up the insertion point.
1300
1301 // Try to split the block so it's fully aligned. Compute the latest split
1302 // point where we can add a 4-byte branch instruction, and then
1303 // WorstCaseAlign to LogAlign.
1304 unsigned LogAlign = MF->getAlignment();
1305 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1306 unsigned KnownBits = UserBBI.internalKnownBits();
1307 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001308 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001309 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1310 BaseInsertOffset));
1311
1312 // Account for alignment and unknown padding.
1313 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1314 BaseInsertOffset -= UPad;
1315
1316 // The 4 in the following is for the unconditional branch we'll be inserting
1317 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach7a465252012-03-23 23:07:03 +00001318 // inside isOffsetInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001319 BaseInsertOffset -= 4;
1320
1321 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1322 << " la=" << LogAlign
1323 << " kb=" << KnownBits
1324 << " up=" << UPad << '\n');
1325
1326 // This could point off the end of the block if we've already got constant
1327 // pool entries following this block; only the last one is in the water list.
1328 // Back past any possible branches (allow for a conditional and a maximally
1329 // long unconditional).
1330 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1331 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1332 (isThumb1 ? 6 : 8);
1333 unsigned EndInsertOffset =
1334 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1335 CPEMI->getOperand(2).getImm();
1336 MachineBasicBlock::iterator MI = UserMI;
1337 ++MI;
1338 unsigned CPUIndex = CPUserIndex+1;
1339 unsigned NumCPUsers = CPUsers.size();
1340 MachineInstr *LastIT = 0;
1341 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1342 Offset < BaseInsertOffset;
1343 Offset += TII->GetInstSizeInBytes(MI),
1344 MI = llvm::next(MI)) {
1345 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1346 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach7a465252012-03-23 23:07:03 +00001347 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001348 // Shift intertion point by one unit of alignment so it is within reach.
1349 BaseInsertOffset -= 1u << LogAlign;
1350 EndInsertOffset -= 1u << LogAlign;
1351 }
1352 // This is overly conservative, as we don't account for CPEMIs being
1353 // reused within the block, but it doesn't matter much. Also assume CPEs
1354 // are added in order with alignment padding. We may eventually be able
1355 // to pack the aligned CPEs better.
1356 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1357 1u << getCPELogAlign(U.CPEMI)) +
1358 U.CPEMI->getOperand(2).getImm();
1359 CPUIndex++;
1360 }
1361
1362 // Remember the last IT instruction.
1363 if (MI->getOpcode() == ARM::t2IT)
1364 LastIT = MI;
1365 }
1366
1367 --MI;
1368
1369 // Avoid splitting an IT block.
1370 if (LastIT) {
1371 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001372 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001373 if (CC != ARMCC::AL)
1374 MI = LastIT;
1375 }
Jim Grosbach7a465252012-03-23 23:07:03 +00001376 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001377}
1378
Jim Grosbach7a465252012-03-23 23:07:03 +00001379/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001380/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001381/// place in-range. Return true if we changed any addresses (thus must run
1382/// another pass of branch lengthening), false otherwise.
Jim Grosbach7a465252012-03-23 23:07:03 +00001383bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001384 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001385 MachineInstr *UserMI = U.MI;
1386 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001387 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001388 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001389 // Compute this only once, it's expensive.
Jim Grosbach7a465252012-03-23 23:07:03 +00001390 unsigned UserOffset = getUserOffset(U);
Evan Cheng768c9f72007-04-27 08:14:15 +00001391
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001392 // See if the current entry is within range, or there is a clone of it
1393 // in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001394 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001395 if (result==1) return false;
1396 else if (result==2) return true;
1397
1398 // No existing clone of this CPE is within range.
1399 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001400 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001401
Bob Wilsonf98032e2009-10-12 21:23:15 +00001402 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001403 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001404 MachineBasicBlock *NewMBB;
1405 water_iterator IP;
Jim Grosbach7a465252012-03-23 23:07:03 +00001406 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001407 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001408 MachineBasicBlock *WaterBB = *IP;
1409
1410 // If the original WaterList entry was "new water" on this iteration,
1411 // propagate that to the new island. This is just keeping NewWaterList
1412 // updated to match the WaterList, which will be updated below.
1413 if (NewWaterList.count(WaterBB)) {
1414 NewWaterList.erase(WaterBB);
1415 NewWaterList.insert(NewIsland);
1416 }
1417 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001418 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001419
1420 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001421 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001422 DEBUG(dbgs() << "No water found\n");
Jim Grosbach7a465252012-03-23 23:07:03 +00001423 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001424
Jim Grosbach7a465252012-03-23 23:07:03 +00001425 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilsonb9239532009-10-15 20:49:47 +00001426 // called while handling branches so that the water will be seen on the
1427 // next iteration for constant pools, but in this context, we don't want
1428 // it. Check for this so it will be removed from the WaterList.
1429 // Also remove any entry from NewWaterList.
1430 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1431 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1432 if (IP != WaterList.end())
1433 NewWaterList.erase(WaterBB);
1434
1435 // We are adding new water. Update NewWaterList.
1436 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001437 }
1438
Bob Wilsonb9239532009-10-15 20:49:47 +00001439 // Remove the original WaterList entry; we want subsequent insertions in
1440 // this vicinity to go after the one we're about to insert. This
1441 // considerably reduces the number of times we have to move the same CPE
1442 // more than once and is also important to ensure the algorithm terminates.
1443 if (IP != WaterList.end())
1444 WaterList.erase(IP);
1445
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001446 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001447 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001448
1449 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +00001450 updateForInsertedWaterBlock(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001451
1452 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach7a465252012-03-23 23:07:03 +00001453 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001454
1455 // Now that we have an island to add the CPE to, clone the original CPE and
1456 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001457 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001458 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001459 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001460 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001461 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001462
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001463 // Mark the basic block as aligned as required by the const-pool entry.
1464 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001465
Evan Chenga8e29892007-01-19 07:51:42 +00001466 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001467 BBInfo[NewIsland->getNumber()].Size += Size;
Jim Grosbach7a465252012-03-23 23:07:03 +00001468 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001469
Evan Chenga8e29892007-01-19 07:51:42 +00001470 // Finally, change the CPI in the instruction operand to be ID.
1471 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001472 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001473 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001474 break;
1475 }
Bob Wilson84945262009-05-12 17:09:30 +00001476
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001477 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001478 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001479
Evan Chenga8e29892007-01-19 07:51:42 +00001480 return true;
1481}
1482
Jim Grosbach7a465252012-03-23 23:07:03 +00001483/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Chenged884f32007-04-03 23:39:48 +00001484/// sizes and offsets of impacted basic blocks.
Jim Grosbach7a465252012-03-23 23:07:03 +00001485void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Chenged884f32007-04-03 23:39:48 +00001486 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001487 unsigned Size = CPEMI->getOperand(2).getImm();
1488 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001489 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001490 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001491 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001492 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001493
1494 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1495 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001496 } else
1497 // Entries are sorted by descending alignment, so realign from the front.
1498 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1499
Jim Grosbach7a465252012-03-23 23:07:03 +00001500 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001501 // An island has only one predecessor BB and one successor BB. Check if
1502 // this BB's predecessor jumps directly to this BB's successor. This
1503 // shouldn't happen currently.
1504 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1505 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001506}
1507
Jim Grosbach7a465252012-03-23 23:07:03 +00001508/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Chenged884f32007-04-03 23:39:48 +00001509/// are zero.
Jim Grosbach7a465252012-03-23 23:07:03 +00001510bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Chenged884f32007-04-03 23:39:48 +00001511 unsigned MadeChange = false;
1512 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1513 std::vector<CPEntry> &CPEs = CPEntries[i];
1514 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1515 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001516 removeDeadCPEMI(CPEs[j].CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001517 CPEs[j].CPEMI = NULL;
1518 MadeChange = true;
1519 }
1520 }
Bob Wilson84945262009-05-12 17:09:30 +00001521 }
Evan Chenged884f32007-04-03 23:39:48 +00001522 return MadeChange;
1523}
1524
Jim Grosbach7a465252012-03-23 23:07:03 +00001525/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001526/// specific BB can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001527bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Chengc0dbec72007-01-31 19:57:44 +00001528 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001529 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach7a465252012-03-23 23:07:03 +00001530 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001531 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001532
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001533 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001534 << " from BB#" << MI->getParent()->getNumber()
1535 << " max delta=" << MaxDisp
Jim Grosbach7a465252012-03-23 23:07:03 +00001536 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattner705e07f2009-08-23 03:41:05 +00001537 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001538
Dale Johannesen8593e412007-04-29 19:19:30 +00001539 if (BrOffset <= DestOffset) {
1540 // Branch before the Dest.
1541 if (DestOffset-BrOffset <= MaxDisp)
1542 return true;
1543 } else {
1544 if (BrOffset-DestOffset <= MaxDisp)
1545 return true;
1546 }
1547 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001548}
1549
Jim Grosbach7a465252012-03-23 23:07:03 +00001550/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001551/// away to fit in its displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001552bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001553 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001554 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001555
Evan Chengc0dbec72007-01-31 19:57:44 +00001556 // Check to see if the DestBB is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001557 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001558 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001559
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001560 if (!Br.isCond)
Jim Grosbach7a465252012-03-23 23:07:03 +00001561 return fixupUnconditionalBr(Br);
1562 return fixupConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001563}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001564
Jim Grosbach7a465252012-03-23 23:07:03 +00001565/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001566/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001567/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001568/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001569bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001570ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001571 MachineInstr *MI = Br.MI;
1572 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001573 if (!isThumb1)
Jim Grosbach7a465252012-03-23 23:07:03 +00001574 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001575
1576 // Use BL to implement far jump.
1577 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001578 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001579 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001580 adjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001581 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001582 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001583
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001584 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001585
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001586 return true;
1587}
1588
Jim Grosbach7a465252012-03-23 23:07:03 +00001589/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001590/// far away to fit in its displacement field. It is converted to an inverse
1591/// conditional branch + an unconditional branch to the destination.
1592bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001593ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001594 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001595 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001596
Bob Wilson39bf0512009-05-12 17:35:29 +00001597 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001598 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001599 // blt L1
1600 // =>
1601 // bge L2
1602 // b L1
1603 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001604 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001605 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001606 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001607
1608 // If the branch is at the end of its MBB and that has a fall-through block,
1609 // direct the updated conditional branch to the fall-through block. Otherwise,
1610 // split the MBB before the next instruction.
1611 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001612 MachineInstr *BMI = &MBB->back();
1613 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001614
Dan Gohmanfe601042010-06-22 15:08:57 +00001615 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001616 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001617 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001618 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001619 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001620 // condition and swap destinations:
1621 // beq L1
1622 // b L2
1623 // =>
1624 // bne L2
1625 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001626 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001627 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001628 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001629 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001630 BMI->getOperand(0).setMBB(DestBB);
1631 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001632 MI->getOperand(1).setImm(CC);
1633 return true;
1634 }
1635 }
1636 }
1637
1638 if (NeedSplit) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001639 splitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001640 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001641 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001642 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001643 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001644 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001645 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001646 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001647 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001648
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001649 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001650 << " also invert condition and change dest. to BB#"
1651 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001652
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001653 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001654 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001655 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001656 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001657 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001658 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001659 if (isThumb)
1660 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1661 .addImm(ARMCC::AL).addReg(0);
1662 else
1663 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001664 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001665 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001666 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001667
1668 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001669 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001670 MI->eraseFromParent();
Jim Grosbach7a465252012-03-23 23:07:03 +00001671 adjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001672 return true;
1673}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001674
Jim Grosbach7a465252012-03-23 23:07:03 +00001675/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001676/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1677/// to do this if tBfar is not used.
Jim Grosbach7a465252012-03-23 23:07:03 +00001678bool ARMConstantIslands::undoLRSpillRestore() {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001679 bool MadeChange = false;
1680 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1681 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001682 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001683 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001684 MI->getOperand(2).getReg() == ARM::PC &&
1685 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001686 // Create the new insn and copy the predicate from the old.
1687 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1688 .addOperand(MI->getOperand(0))
1689 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001690 MI->eraseFromParent();
1691 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001692 }
1693 }
1694 return MadeChange;
1695}
Evan Cheng5657c012009-07-29 02:18:14 +00001696
Jim Grosbach7a465252012-03-23 23:07:03 +00001697// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001698// below may shrink MI.
1699bool
1700ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1701 switch(MI->getOpcode()) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001702 // optimizeThumb2Instructions.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001703 case ARM::t2LEApcrel:
1704 case ARM::t2LDRpci:
Jim Grosbach7a465252012-03-23 23:07:03 +00001705 // optimizeThumb2Branches.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001706 case ARM::t2B:
1707 case ARM::t2Bcc:
1708 case ARM::tBcc:
Jim Grosbach7a465252012-03-23 23:07:03 +00001709 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001710 case ARM::t2BR_JT:
1711 return true;
1712 }
1713 return false;
1714}
1715
Jim Grosbach7a465252012-03-23 23:07:03 +00001716bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001717 bool MadeChange = false;
1718
1719 // Shrink ADR and LDR from constantpool.
1720 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1721 CPUser &U = CPUsers[i];
1722 unsigned Opcode = U.MI->getOpcode();
1723 unsigned NewOpc = 0;
1724 unsigned Scale = 1;
1725 unsigned Bits = 0;
1726 switch (Opcode) {
1727 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001728 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001729 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1730 NewOpc = ARM::tLEApcrel;
1731 Bits = 8;
1732 Scale = 4;
1733 }
1734 break;
1735 case ARM::t2LDRpci:
1736 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1737 NewOpc = ARM::tLDRpci;
1738 Bits = 8;
1739 Scale = 4;
1740 }
1741 break;
1742 }
1743
1744 if (!NewOpc)
1745 continue;
1746
Jim Grosbach7a465252012-03-23 23:07:03 +00001747 unsigned UserOffset = getUserOffset(U);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001748 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001749
1750 // Be conservative with inline asm.
1751 if (!U.KnownAlignment)
1752 MaxOffs -= 2;
1753
Evan Chenga1efbbd2009-08-14 00:32:16 +00001754 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach7a465252012-03-23 23:07:03 +00001755 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001756 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001757 U.MI->setDesc(TII->get(NewOpc));
1758 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001759 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001760 adjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001761 ++NumT2CPShrunk;
1762 MadeChange = true;
1763 }
1764 }
1765
Jim Grosbach7a465252012-03-23 23:07:03 +00001766 MadeChange |= optimizeThumb2Branches();
1767 MadeChange |= optimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001768 return MadeChange;
1769}
1770
Jim Grosbach7a465252012-03-23 23:07:03 +00001771bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001772 bool MadeChange = false;
1773
1774 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1775 ImmBranch &Br = ImmBranches[i];
1776 unsigned Opcode = Br.MI->getOpcode();
1777 unsigned NewOpc = 0;
1778 unsigned Scale = 1;
1779 unsigned Bits = 0;
1780 switch (Opcode) {
1781 default: break;
1782 case ARM::t2B:
1783 NewOpc = ARM::tB;
1784 Bits = 11;
1785 Scale = 2;
1786 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001787 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001788 NewOpc = ARM::tBcc;
1789 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001790 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001791 break;
1792 }
Evan Chengde17fb62009-10-31 23:46:45 +00001793 }
1794 if (NewOpc) {
1795 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1796 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001797 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001798 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Chengde17fb62009-10-31 23:46:45 +00001799 Br.MI->setDesc(TII->get(NewOpc));
1800 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001801 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001802 adjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001803 ++NumT2BrShrunk;
1804 MadeChange = true;
1805 }
1806 }
1807
1808 Opcode = Br.MI->getOpcode();
1809 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001810 continue;
1811
Evan Chengbfe8afa2012-01-14 01:53:46 +00001812 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1813 // so this transformation is not safe.
1814 if (!Br.MI->killsRegister(ARM::CPSR))
1815 continue;
1816
Evan Chengde17fb62009-10-31 23:46:45 +00001817 NewOpc = 0;
1818 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001819 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Chengde17fb62009-10-31 23:46:45 +00001820 if (Pred == ARMCC::EQ)
1821 NewOpc = ARM::tCBZ;
1822 else if (Pred == ARMCC::NE)
1823 NewOpc = ARM::tCBNZ;
1824 if (!NewOpc)
1825 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001826 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001827 // Check if the distance is within 126. Subtract starting offset by 2
1828 // because the cmp will be eliminated.
Jim Grosbach7a465252012-03-23 23:07:03 +00001829 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001830 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001831 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001832 MachineBasicBlock::iterator CmpMI = Br.MI;
1833 if (CmpMI != Br.MI->getParent()->begin()) {
1834 --CmpMI;
1835 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1836 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperc89c7442012-03-27 07:21:54 +00001837 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng0539c152011-04-01 22:09:28 +00001838 if (Pred == ARMCC::AL &&
1839 CmpMI->getOperand(1).getImm() == 0 &&
1840 isARMLowRegister(Reg)) {
1841 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001842 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng0539c152011-04-01 22:09:28 +00001843 MachineInstr *NewBR =
1844 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1845 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1846 CmpMI->eraseFromParent();
1847 Br.MI->eraseFromParent();
1848 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001849 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001850 adjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001851 ++NumCBZ;
1852 MadeChange = true;
1853 }
Evan Chengde17fb62009-10-31 23:46:45 +00001854 }
1855 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001856 }
1857 }
1858
1859 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001860}
1861
Jim Grosbach7a465252012-03-23 23:07:03 +00001862/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chenga1efbbd2009-08-14 00:32:16 +00001863/// jumptables when it's possible.
Jim Grosbach7a465252012-03-23 23:07:03 +00001864bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001865 bool MadeChange = false;
1866
1867 // FIXME: After the tables are shrunk, can we get rid some of the
1868 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001869 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001870 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001871
Evan Cheng5657c012009-07-29 02:18:14 +00001872 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1873 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1874 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001875 const MCInstrDesc &MCID = MI->getDesc();
1876 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001877 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001878 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1879 unsigned JTI = JTOP.getIndex();
1880 assert(JTI < JT.size());
1881
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001882 bool ByteOk = true;
1883 bool HalfWordOk = true;
Jim Grosbach7a465252012-03-23 23:07:03 +00001884 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach80697d12009-11-12 17:25:07 +00001885 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001886 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1887 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001888 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001889 // Negative offset is not ok. FIXME: We should change BB layout to make
1890 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001891 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001892 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001893 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001894 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001895 HalfWordOk = false;
1896 if (!ByteOk && !HalfWordOk)
1897 break;
1898 }
1899
1900 if (ByteOk || HalfWordOk) {
1901 MachineBasicBlock *MBB = MI->getParent();
1902 unsigned BaseReg = MI->getOperand(0).getReg();
1903 bool BaseRegKill = MI->getOperand(0).isKill();
1904 if (!BaseRegKill)
1905 continue;
1906 unsigned IdxReg = MI->getOperand(1).getReg();
1907 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001908
1909 // Scan backwards to find the instruction that defines the base
1910 // register. Due to post-RA scheduling, we can't count on it
1911 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001912 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001913 MachineBasicBlock::iterator B = MBB->begin();
1914 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1915 --PrevI;
1916
1917 // If for some reason we didn't find it, we can't do anything, so
1918 // just skip this one.
1919 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001920 continue;
1921
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001922 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001923 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001924 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001925 // Make sure it only defines the base register and kills any uses
1926 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001927 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1928 const MachineOperand &MO = AddrMI->getOperand(k);
1929 if (!MO.isReg() || !MO.getReg())
1930 continue;
1931 if (MO.isDef() && MO.getReg() != BaseReg) {
1932 OptOk = false;
1933 break;
1934 }
1935 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1936 OptOk = false;
1937 break;
1938 }
1939 }
1940 if (!OptOk)
1941 continue;
1942
Owen Anderson6b8719f2010-12-13 22:51:08 +00001943 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001944 // that gave us the initial base register definition.
1945 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1946 ;
1947
Owen Anderson6b8719f2010-12-13 22:51:08 +00001948 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001949 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001950 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001951 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001952 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001953 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001954 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001955
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001956 if (!OptOk)
1957 continue;
1958
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001959 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1960 << " lea: " << *LeaMI);
Jim Grosbachd092a872010-11-29 21:28:32 +00001961 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001962 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1963 .addReg(IdxReg, getKillRegState(IdxRegKill))
1964 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1965 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001966 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001967 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1968 // is 2-byte aligned. For now, asm printer will fix it up.
1969 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1970 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1971 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1972 OrigSize += TII->GetInstSizeInBytes(MI);
1973
1974 AddrMI->eraseFromParent();
1975 LeaMI->eraseFromParent();
1976 MI->eraseFromParent();
1977
1978 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001979 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001980 adjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001981
1982 ++NumTBs;
1983 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001984 }
1985 }
1986
1987 return MadeChange;
1988}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001989
Jim Grosbach7a465252012-03-23 23:07:03 +00001990/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach9249efe2009-11-16 18:55:47 +00001991/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach7a465252012-03-23 23:07:03 +00001992bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001993 bool MadeChange = false;
1994
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001995 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001996 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001997
Jim Grosbach80697d12009-11-12 17:25:07 +00001998 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1999 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2000 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00002001 const MCInstrDesc &MCID = MI->getDesc();
2002 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00002003 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00002004 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2005 unsigned JTI = JTOP.getIndex();
2006 assert(JTI < JT.size());
2007
2008 // We prefer if target blocks for the jump table come after the jump
2009 // instruction so we can use TB[BH]. Loop through the target blocks
2010 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00002011 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00002012 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2013 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2014 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00002015 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00002016
Jim Grosbach08cbda52009-11-16 18:58:52 +00002017 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002018 // The destination precedes the switch. Try to move the block forward
2019 // so we have a positive offset.
2020 MachineBasicBlock *NewBB =
Jim Grosbach7a465252012-03-23 23:07:03 +00002021 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach80697d12009-11-12 17:25:07 +00002022 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002023 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00002024 MadeChange = true;
2025 }
2026 }
2027 }
2028
2029 return MadeChange;
2030}
2031
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002032MachineBasicBlock *ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +00002033adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach03e2d442010-07-07 22:53:35 +00002034 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00002035 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00002036 // table that branches back to the actual target. This is a very simple
2037 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00002038 MachineBasicBlock *TBB = 0, *FBB = 0;
2039 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002040 SmallVector<MachineOperand, 4> CondPrior;
2041 MachineFunction::iterator BBi = BB;
2042 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002043
Jim Grosbachca215e72009-11-16 17:10:56 +00002044 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002045 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00002046
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002047 // If the block ends in an unconditional branch, move it. The prior block
2048 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00002049 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002050 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002051 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002052 BB->moveAfter(JTBB);
2053 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002054 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00002055 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002056 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00002057 ++NumJTMoved;
2058 return NULL;
2059 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002060
2061 // Create a new MBB for the code after the jump BB.
2062 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002063 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002064 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002065 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002066
2067 // Add an unconditional branch from NewBB to BB.
2068 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2069 // correspond directly to anything in the source.
2070 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00002071 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2072 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002073
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002074 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002075 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002076
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002077 // Update the CFG.
2078 NewBB->addSuccessor(BB);
2079 JTBB->removeSuccessor(BB);
2080 JTBB->addSuccessor(NewBB);
2081
Jim Grosbach80697d12009-11-12 17:25:07 +00002082 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002083 return NewBB;
2084}