blob: 25fabca4ab9b2b484ea489ff915c8594ce3f018a [file] [log] [blame]
Bill Wendling18581a42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Cheng10043e22007-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
Evan Cheng10043e22007-01-19 07:51:42 +000016#include "ARM.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000017#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000018#include "MCTargetDesc/ARMAddressingModes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "Thumb2InstrInfo.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000024#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/CommandLine.h"
Evan Cheng10043e22007-01-19 07:51:42 +000030#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000032#include "llvm/Support/Format.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetMachine.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000035#include <algorithm>
Evan Cheng10043e22007-01-19 07:51:42 +000036using namespace llvm;
37
Chandler Carruth84e68b22014-04-22 02:41:26 +000038#define DEBUG_TYPE "arm-cp-islands"
39
Evan Chengdb73d682009-08-14 00:32:16 +000040STATISTIC(NumCPEs, "Number of constpool entries");
41STATISTIC(NumSplit, "Number of uncond branches inserted");
42STATISTIC(NumCBrFixed, "Number of cond branches fixed");
43STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
44STATISTIC(NumTBs, "Number of table branches generated");
45STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000046STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000047STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000048STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000049STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000050
51
52static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000053AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000054 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000055
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000056static cl::opt<unsigned>
57CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
58 cl::desc("The max number of iteration for converge"));
59
60
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +000061/// UnknownPadding - Return the worst case padding that could result from
62/// unknown offset bits. This does not include alignment padding caused by
63/// known offset bits.
64///
65/// @param LogAlign log2(alignment)
66/// @param KnownBits Number of known low offset bits.
67static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
68 if (KnownBits < LogAlign)
69 return (1u << LogAlign) - (1u << KnownBits);
70 return 0;
71}
72
Evan Cheng10043e22007-01-19 07:51:42 +000073namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000074 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000075 /// requires constant pool entries to be scattered among the instructions
76 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000077 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000078 /// special instructions.
79 ///
80 /// The terminology used in this pass includes:
81 /// Islands - Clumps of constants placed in the function.
82 /// Water - Potential places where an island could be formed.
83 /// CPE - A constant pool entry that has been placed somewhere, which
84 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000085 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000086 /// BasicBlockInfo - Information about the offset and size of a single
87 /// basic block.
88 struct BasicBlockInfo {
89 /// Offset - Distance from the beginning of the function to the beginning
90 /// of this basic block.
91 ///
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +000092 /// Offsets are computed assuming worst case padding before an aligned
93 /// block. This means that subtracting basic block offsets always gives a
94 /// conservative estimate of the real distance which may be smaller.
95 ///
96 /// Because worst case padding is used, the computed offset of an aligned
97 /// block may not actually be aligned.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000098 unsigned Offset;
Bob Wilson2f4e56f2009-05-12 17:09:30 +000099
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000100 /// Size - Size of the basic block in bytes. If the block contains
101 /// inline assembly, this is a worst case estimate.
102 ///
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000103 /// The size does not include any alignment padding whether from the
104 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000105 unsigned Size;
106
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000107 /// KnownBits - The number of low bits in Offset that are known to be
108 /// exact. The remaining bits of Offset are an upper bound.
109 uint8_t KnownBits;
110
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000111 /// Unalign - When non-zero, the block contains instructions (inline asm)
112 /// of unknown size. The real size may be smaller than Size bytes by a
113 /// multiple of 1 << Unalign.
114 uint8_t Unalign;
115
116 /// PostAlign - When non-zero, the block terminator contains a .align
117 /// directive, so the end of the block is aligned to 1 << PostAlign
118 /// bytes.
119 uint8_t PostAlign;
120
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000121 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
122 PostAlign(0) {}
Jakob Stoklund Olesenaf748e12011-12-07 01:22:52 +0000123
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000124 /// Compute the number of known offset bits internally to this block.
125 /// This number should be used to predict worst case padding when
126 /// splitting the block.
127 unsigned internalKnownBits() const {
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000128 unsigned Bits = Unalign ? Unalign : KnownBits;
129 // If the block size isn't a multiple of the known bits, assume the
130 // worst case padding.
131 if (Size & ((1u << Bits) - 1))
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000132 Bits = countTrailingZeros(Size);
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000133 return Bits;
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000134 }
135
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000136 /// Compute the offset immediately following this block. If LogAlign is
137 /// specified, return the offset the successor block will get if it has
138 /// this alignment.
139 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000140 unsigned PO = Offset + Size;
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000141 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
142 if (!LA)
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000143 return PO;
144 // Add alignment padding from the terminator.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +0000145 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000146 }
147
148 /// Compute the number of known low bits of postOffset. If this block
149 /// contains inline asm, the number of known bits drops to the
150 /// instruction alignment. An aligned terminator may increase the number
151 /// of know bits.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000152 /// If LogAlign is given, also consider the alignment of the next block.
153 unsigned postKnownBits(unsigned LogAlign = 0) const {
154 return std::max(std::max(unsigned(PostAlign), LogAlign),
155 internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000156 }
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000157 };
158
159 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000160
Evan Cheng10043e22007-01-19 07:51:42 +0000161 /// WaterList - A sorted list of basic blocks where islands could be placed
162 /// (i.e. blocks that don't fall through to the following block, due
163 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000164 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000165
Bob Wilson2f9be502009-10-15 20:49:47 +0000166 /// NewWaterList - The subset of WaterList that was created since the
167 /// previous iteration by inserting unconditional branches.
168 SmallSet<MachineBasicBlock*, 4> NewWaterList;
169
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000170 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
171
Evan Cheng10043e22007-01-19 07:51:42 +0000172 /// CPUser - One user of a constant pool, keeping the machine instruction
173 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000174 /// allowed from the instruction to the CP. The HighWaterMark records the
175 /// highest basic block where a new CPEntry can be placed. To ensure this
176 /// pass terminates, the CP entries are initially placed at the end of the
177 /// function and then move monotonically to lower addresses. The
178 /// exception to this rule is when the current CP entry for a particular
179 /// CPUser is out of range, but there is another CP entry for the same
180 /// constant value in range. We want to use the existing in-range CP
181 /// entry, but if it later moves out of range, the search for new water
182 /// should resume where it left off. The HighWaterMark is used to record
183 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000184 struct CPUser {
185 MachineInstr *MI;
186 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000187 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000188 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000189 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000190 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000191 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000192 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
193 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000194 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
195 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000196 HighWaterMark = CPEMI->getParent();
197 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000198 /// getMaxDisp - Returns the maximum displacement supported by MI.
199 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000200 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000201 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000202 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000203 }
Evan Cheng10043e22007-01-19 07:51:42 +0000204 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000205
Evan Cheng10043e22007-01-19 07:51:42 +0000206 /// CPUsers - Keep track of all of the machine instructions that use various
207 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000208 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000209
Evan Cheng8b7700f2007-02-09 20:54:44 +0000210 /// CPEntry - One per constant pool entry, keeping the machine instruction
211 /// pointer, the constpool index, and the number of CPUser's which
212 /// reference this entry.
213 struct CPEntry {
214 MachineInstr *CPEMI;
215 unsigned CPI;
216 unsigned RefCount;
217 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
218 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
219 };
220
221 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000222 /// instructions. For each original constpool index (i.e. those that existed
223 /// upon entry to this pass), it keeps a vector of entries. Original
224 /// elements are cloned as we go along; the clones are put in the vector of
225 /// the original element, but have distinct CPIs.
226 ///
227 /// The first half of CPEntries contains generic constants, the second half
228 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
229 /// which vector it will be in here.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000230 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000231
Tim Northovera603c402015-05-31 19:22:07 +0000232 /// Maps a JT index to the offset in CPEntries containing copies of that
233 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
234 DenseMap<int, int> JumpTableEntryIndices;
235
236 /// Maps a JT index to the LEA that actually uses the index to calculate its
237 /// base address.
238 DenseMap<int, int> JumpTableUserIndices;
239
Evan Cheng22c7cf52007-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 Cheng010ae382007-01-25 23:18:59 +0000246 unsigned MaxDisp : 31;
247 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000248 unsigned UncondBr;
249 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000250 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000251 };
252
Evan Chengc95f95b2007-05-16 05:14:06 +0000253 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000254 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000255 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000256
Evan Cheng7fa69642007-01-30 01:18:38 +0000257 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
258 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000259 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000260
Evan Chengc6d70ae2009-07-29 02:18:14 +0000261 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
262 SmallVector<MachineInstr*, 4> T2JumpTables;
263
Evan Cheng7fa69642007-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 Olesen2a759972011-12-12 18:16:53 +0000268 MachineFunction *MF;
269 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000270 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000271 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000272 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000273 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000274 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000275 bool isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +0000276 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000277 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000278 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000279
Craig Topper6bc27bf2014-03-10 02:09:33 +0000280 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000281
Craig Topper6bc27bf2014-03-10 02:09:33 +0000282 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000283 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000284 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000285
Evan Cheng10043e22007-01-19 07:51:42 +0000286 private:
Tim Northovera603c402015-05-31 19:22:07 +0000287 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
288 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000289 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000290 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000291 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000292 void scanFunctionJumpTables();
293 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
294 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
295 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
296 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
297 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000298 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000299 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
300 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000301 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000302 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000303 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000304 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000305 void removeDeadCPEMI(MachineInstr *CPEMI);
306 bool removeUnusedCPEntries();
307 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
308 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
309 bool DoDump = false);
310 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000311 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000312 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
313 bool fixupImmediateBr(ImmBranch &Br);
314 bool fixupConditionalBr(ImmBranch &Br);
315 bool fixupUnconditionalBr(ImmBranch &Br);
316 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000317 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000318 bool optimizeThumb2Instructions();
319 bool optimizeThumb2Branches();
320 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000321 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
322 unsigned &DeadSize, bool &CanDeleteLEA,
323 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000324 bool optimizeThumb2JumpTables();
325 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000326 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000327
Jim Grosbach190e7b62012-03-23 23:07:03 +0000328 void computeBlockSize(MachineBasicBlock *MBB);
329 unsigned getOffsetOf(MachineInstr *MI) const;
330 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000331 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000332 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000333
Jim Grosbach190e7b62012-03-23 23:07:03 +0000334 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000335 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000336 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000337 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000338 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000339 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000340 }
Evan Cheng10043e22007-01-19 07:51:42 +0000341 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000342 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000343}
Evan Cheng10043e22007-01-19 07:51:42 +0000344
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000345/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000346void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000347#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000348 assert(std::is_sorted(MF->begin(), MF->end(),
349 [this](const MachineBasicBlock &LHS,
350 const MachineBasicBlock &RHS) {
351 return BBInfo[LHS.getNumber()].postOffset() <
352 BBInfo[RHS.getNumber()].postOffset();
353 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000354 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000355 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
356 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000357 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000358 // Verify offset using the real max displacement without the safety
359 // adjustment.
360 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000361 /* DoDump = */ true)) {
362 DEBUG(dbgs() << "OK\n");
363 continue;
364 }
365 DEBUG(dbgs() << "Out of range.\n");
366 dumpBBs();
367 DEBUG(MF->dump());
368 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000369 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000370#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000371}
372
373/// print block size and offset information - debugging
374void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000375 DEBUG({
376 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
377 const BasicBlockInfo &BBI = BBInfo[J];
378 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
379 << " kb=" << unsigned(BBI.KnownBits)
380 << " ua=" << unsigned(BBI.Unalign)
381 << " pa=" << unsigned(BBI.PostAlign)
382 << format(" size=%#x\n", BBInfo[J].Size);
383 }
384 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000385}
386
Evan Cheng22c7cf52007-01-25 03:12:46 +0000387/// createARMConstantIslandPass - returns an instance of the constpool
388/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000389FunctionPass *llvm::createARMConstantIslandPass() {
390 return new ARMConstantIslands();
391}
392
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000393bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
394 MF = &mf;
395 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000396
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000397 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000398 << MCP->getConstants().size() << " CP entries, aligned to "
399 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000400
Eric Christopher1b21f002015-01-29 00:19:33 +0000401 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
402 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000403 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000404
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000405 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000406 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000407 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000408
409 HasFarJump = false;
410
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000411 // This pass invalidates liveness information when it splits basic blocks.
412 MF->getRegInfo().invalidateLiveness();
413
Evan Cheng10043e22007-01-19 07:51:42 +0000414 // Renumber all of the machine basic blocks in the function, guaranteeing that
415 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000416 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000417
Jim Grosbach5d577142009-11-12 17:25:07 +0000418 // Try to reorder and otherwise adjust the block layout to make good use
419 // of the TB[BH] instructions.
420 bool MadeChange = false;
421 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000422 scanFunctionJumpTables();
423 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000424 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000425 T2JumpTables.clear();
426 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000427 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000428 }
429
Evan Cheng10043e22007-01-19 07:51:42 +0000430 // Perform the initial placement of the constant pool entries. To start with,
431 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000432 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000433 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000434 doInitialConstPlacement(CPEMIs);
435
436 if (MF->getJumpTableInfo())
437 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000438
Evan Cheng10043e22007-01-19 07:51:42 +0000439 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000440 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000441
Evan Cheng10043e22007-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 Grosbach190e7b62012-03-23 23:07:03 +0000445 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000446 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000447 DEBUG(dumpBBs());
448
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000449 // Functions with jump tables need an alignment of 4 because they use the ADR
450 // instruction, which aligns the PC to 4 bytes before adding an offset.
451 if (!T2JumpTables.empty())
452 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000453
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000454 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000455 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000456
Evan Cheng7fa69642007-01-30 01:18:38 +0000457 // Iteratively place constant pool entries and fix up branches until there
458 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000459 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000460 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000461 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000462 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000463 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000464 // For most inputs, it converges in no more than 5 iterations.
465 // If it doens't end in 10, the input may have huge BB or many CPEs.
466 // In this case, we will try differnt heuristics.
467 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
468 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000469 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000470 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000471
Bob Wilson2f9be502009-10-15 20:49:47 +0000472 // Clear NewWaterList now. If we split a block for branches, it should
473 // appear as "new water" for the next iteration of constant pool placement.
474 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000475
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000476 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000477 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000478 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000479 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000480 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000481 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000482 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000483
484 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000485 break;
486 MadeChange = true;
487 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000488
Bradley Smitha1189102016-01-15 10:26:17 +0000489 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000490 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000491 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000492
Bradley Smitha1189102016-01-15 10:26:17 +0000493 // Shrink 32-bit branch instructions.
494 if (isThumb && STI->hasV8MBaselineOps())
495 MadeChange |= optimizeThumb2Branches();
496
497 // Optimize jump tables using TBB / TBH.
498 if (isThumb2)
499 MadeChange |= optimizeThumb2JumpTables();
500
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000501 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000502 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000503
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000504 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
505 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000506 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000507 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000508
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000509 // Save the mapping between original and cloned constpool entries.
510 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
511 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
512 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000513 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
514 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000515 }
516 }
517
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000518 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000519
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000520 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000521 WaterList.clear();
522 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000523 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000524 JumpTableEntryIndices.clear();
525 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000526 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000527 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000528 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000529
530 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000531}
532
Tim Northovera603c402015-05-31 19:22:07 +0000533/// \brief Perform the initial placement of the regular constant pool entries.
534/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000535void
Tim Northovera603c402015-05-31 19:22:07 +0000536ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000537 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000538 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
539 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000540
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000541 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000542 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000543
544 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000545 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000546
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000547 // The function needs to be as aligned as the basic blocks. The linker may
548 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000549 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000550
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000551 // Order the entries in BB by descending alignment. That ensures correct
552 // alignment of all entries as long as BB is sufficiently aligned. Keep
553 // track of the insertion point for each alignment. We are going to bucket
554 // sort the entries as they are created.
555 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000556
Evan Cheng10043e22007-01-19 07:51:42 +0000557 // Add all of the constants from the constant pool to the end block, use an
558 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000559 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000560
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000561 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000562 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000563 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000564 assert(Size >= 4 && "Too small constant pool entry");
565 unsigned Align = CPs[i].getAlignment();
566 assert(isPowerOf2_32(Align) && "Invalid alignment");
567 // Verify that all constant pool entries are a multiple of their alignment.
568 // If not, we would have to pad them out so that instructions stay aligned.
569 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
570
571 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
572 unsigned LogAlign = Log2_32(Align);
573 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000574 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000575 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000576 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000577 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000578
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000579 // Ensure that future entries with higher alignment get inserted before
580 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000581 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000582 if (InsPoint[a] == InsAt)
583 InsPoint[a] = CPEMI;
584
Evan Cheng8b7700f2007-02-09 20:54:44 +0000585 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000586 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000587 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000588 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
589 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000590 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000591 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000592}
593
Tim Northovera603c402015-05-31 19:22:07 +0000594/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
595/// instructions can be made more efficient if the jump table immediately
596/// follows the instruction, it's best to place them immediately next to their
597/// jumps to begin with. In almost all cases they'll never be moved from that
598/// position.
599void ARMConstantIslands::doInitialJumpTablePlacement(
600 std::vector<MachineInstr *> &CPEMIs) {
601 unsigned i = CPEntries.size();
602 auto MJTI = MF->getJumpTableInfo();
603 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
604
605 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
606 for (MachineBasicBlock &MBB : *MF) {
607 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000608 if (MI == MBB.end())
609 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000610
611 unsigned JTOpcode;
612 switch (MI->getOpcode()) {
613 default:
614 continue;
615 case ARM::BR_JTadd:
616 case ARM::BR_JTr:
617 case ARM::tBR_JTr:
618 case ARM::BR_JTm:
619 JTOpcode = ARM::JUMPTABLE_ADDRS;
620 break;
621 case ARM::t2BR_JT:
622 JTOpcode = ARM::JUMPTABLE_INSTS;
623 break;
624 case ARM::t2TBB_JT:
625 JTOpcode = ARM::JUMPTABLE_TBB;
626 break;
627 case ARM::t2TBH_JT:
628 JTOpcode = ARM::JUMPTABLE_TBH;
629 break;
630 }
631
632 unsigned NumOps = MI->getDesc().getNumOperands();
633 MachineOperand JTOp =
634 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
635 unsigned JTI = JTOp.getIndex();
636 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
637 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
638 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
639 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
640 DebugLoc(), TII->get(JTOpcode))
641 .addImm(i++)
642 .addJumpTableIndex(JTI)
643 .addImm(Size);
644 CPEMIs.push_back(CPEMI);
645 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
646 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
647 if (!LastCorrectlyNumberedBB)
648 LastCorrectlyNumberedBB = &MBB;
649 }
650
651 // If we did anything then we need to renumber the subsequent blocks.
652 if (LastCorrectlyNumberedBB)
653 MF->RenumberBlocks(LastCorrectlyNumberedBB);
654}
655
Dale Johannesene18b13b2007-02-23 05:02:36 +0000656/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000657/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000658bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000659 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000660 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000661 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000662 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000663 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000664
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000665 MachineBasicBlock *NextBB = &*std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000666 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
667 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000668
Tim Northoverab85dcc2014-11-13 17:58:51 +0000669 // Try to analyze the end of the block. A potential fallthrough may already
670 // have an unconditional branch for whatever reason.
671 MachineBasicBlock *TBB, *FBB;
672 SmallVector<MachineOperand, 4> Cond;
673 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
674 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000675}
676
Evan Cheng8b7700f2007-02-09 20:54:44 +0000677/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
678/// look up the corresponding CPEntry.
679ARMConstantIslands::CPEntry
680*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
681 const MachineInstr *CPEMI) {
682 std::vector<CPEntry> &CPEs = CPEntries[CPI];
683 // Number of entries per constpool index should be small, just do a
684 // linear search.
685 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
686 if (CPEs[i].CPEMI == CPEMI)
687 return &CPEs[i];
688 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000689 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000690}
691
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000692/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000693/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000694unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000695 switch (CPEMI->getOpcode()) {
696 case ARM::CONSTPOOL_ENTRY:
697 break;
698 case ARM::JUMPTABLE_TBB:
699 return 0;
700 case ARM::JUMPTABLE_TBH:
701 case ARM::JUMPTABLE_INSTS:
702 return 1;
703 case ARM::JUMPTABLE_ADDRS:
704 return 2;
705 default:
706 llvm_unreachable("unknown constpool entry kind");
707 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000708
Tim Northovera603c402015-05-31 19:22:07 +0000709 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000710 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
711 unsigned Align = MCP->getConstants()[CPI].getAlignment();
712 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
713 return Log2_32(Align);
714}
715
Jim Grosbach190e7b62012-03-23 23:07:03 +0000716/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000717/// information about the sizes of each block and the locations of all
718/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000719void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000720 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000721 MBBI != E; ++MBBI) {
722 MachineBasicBlock &MBB = *MBBI;
723
Jim Grosbach5d577142009-11-12 17:25:07 +0000724 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000725 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000726 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000727 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000728 }
729}
730
Jim Grosbach190e7b62012-03-23 23:07:03 +0000731/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000732/// information about the sizes of each block, the location of all the water,
733/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000734void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000735initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000736 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000737 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000738
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000739 // First thing, compute the size of all basic blocks, and see if the function
740 // has any inline assembly in it. If so, we have to be conservative about
741 // alignment assumptions, as we don't know for sure the size of any
742 // instructions in the inline assembly.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000743 for (MachineBasicBlock &MBB : *MF)
744 computeBlockSize(&MBB);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000745
746 // The known bits of the entry block offset are determined by the function
747 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000748 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000749
750 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000751 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000752
Bill Wendling18581a42010-12-21 01:54:40 +0000753 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000754 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000755 MBBI != E; ++MBBI) {
756 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000757
Evan Cheng10043e22007-01-19 07:51:42 +0000758 // If this block doesn't fall through into the next MBB, then this is
759 // 'water' that a constant pool island could be placed.
760 if (!BBHasFallthrough(&MBB))
761 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000762
Evan Cheng10043e22007-01-19 07:51:42 +0000763 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
764 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000765 if (I->isDebugValue())
766 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000767
Matthias Braunfa3872e2015-05-18 20:27:55 +0000768 unsigned Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000769 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000770 bool isCond = false;
771 unsigned Bits = 0;
772 unsigned Scale = 1;
773 int UOpc = Opc;
774 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000775 default:
776 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000777 case ARM::t2BR_JT:
778 T2JumpTables.push_back(I);
779 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000780 case ARM::Bcc:
781 isCond = true;
782 UOpc = ARM::B;
783 // Fallthrough
784 case ARM::B:
785 Bits = 24;
786 Scale = 4;
787 break;
788 case ARM::tBcc:
789 isCond = true;
790 UOpc = ARM::tB;
791 Bits = 8;
792 Scale = 2;
793 break;
794 case ARM::tB:
795 Bits = 11;
796 Scale = 2;
797 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000798 case ARM::t2Bcc:
799 isCond = true;
800 UOpc = ARM::t2B;
801 Bits = 20;
802 Scale = 2;
803 break;
804 case ARM::t2B:
805 Bits = 24;
806 Scale = 2;
807 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000808 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000809
810 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000811 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000812 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000813 }
814
Evan Cheng7fa69642007-01-30 01:18:38 +0000815 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
816 PushPopMIs.push_back(I);
817
Tim Northovera603c402015-05-31 19:22:07 +0000818 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
819 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
820 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000821 continue;
822
Evan Cheng10043e22007-01-19 07:51:42 +0000823 // Scan the instructions for constant pool operands.
824 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Tim Northovera603c402015-05-31 19:22:07 +0000825 if (I->getOperand(op).isCPI() || I->getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000826 // We found one. The addressing mode tells us the max displacement
827 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000828
Evan Cheng10043e22007-01-19 07:51:42 +0000829 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000830 unsigned Bits = 0;
831 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000832 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000833 bool IsSoImm = false;
834
835 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000836 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000837 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000838
839 // Taking the address of a CP entry.
840 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000841 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000842 // This takes a SoImm, which is 8 bit immediate rotated. We'll
843 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000844 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000845 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000846 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000847 Scale = 4;
848 NegOk = true;
849 IsSoImm = true;
850 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000851 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000852 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000853 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000854 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000855 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000856 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000857 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000858 Bits = 8;
859 Scale = 4;
860 break;
861
David Majnemer452f1f92013-06-04 17:46:15 +0000862 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000863 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000864 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000865 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000866 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000867 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000868 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000869
870 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000871 Bits = 8;
872 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000873 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000874
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000875 case ARM::VLDRD:
876 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000877 Bits = 8;
878 Scale = 4; // +-(offset_8*4)
879 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000880 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000881 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000882
Evan Cheng10043e22007-01-19 07:51:42 +0000883 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000884 unsigned CPI = I->getOperand(op).getIndex();
Tim Northovera603c402015-05-31 19:22:07 +0000885 if (I->getOperand(op).isJTI()) {
886 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
887 CPI = JumpTableEntryIndices[CPI];
888 }
889
Evan Cheng8b7700f2007-02-09 20:54:44 +0000890 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000891 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000892 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000893
894 // Increment corresponding CPEntry reference count.
895 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
896 assert(CPE && "Cannot find a corresponding CPEntry!");
897 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000898
Evan Cheng10043e22007-01-19 07:51:42 +0000899 // Instructions can only use one CP entry, don't bother scanning the
900 // rest of the operands.
901 break;
902 }
903 }
Evan Cheng10043e22007-01-19 07:51:42 +0000904 }
905}
906
Jim Grosbach190e7b62012-03-23 23:07:03 +0000907/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000908/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000909void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000910 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
911 BBI.Size = 0;
912 BBI.Unalign = 0;
913 BBI.PostAlign = 0;
914
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000915 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
916 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000917 BBI.Size += TII->GetInstSizeInBytes(I);
918 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
919 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000920 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000921 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000922 // Also consider instructions that may be shrunk later.
923 else if (isThumb && mayOptimizeThumb2Instruction(I))
924 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000925 }
926
927 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000928 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000929 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000930 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000931 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000932}
933
Jim Grosbach190e7b62012-03-23 23:07:03 +0000934/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000935/// from the start of the function. This offset changes as stuff is moved
936/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000937unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000938 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000939
Evan Cheng10043e22007-01-19 07:51:42 +0000940 // The offset is composed of two things: the sum of the sizes of all MBB's
941 // before this instruction's block, and the offset from the start of the block
942 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000943 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000944
945 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000946 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000947 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000948 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000949 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000950 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000951}
952
953/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
954/// ID.
955static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
956 const MachineBasicBlock *RHS) {
957 return LHS->getNumber() < RHS->getNumber();
958}
959
Jim Grosbach190e7b62012-03-23 23:07:03 +0000960/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000961/// machine function, it upsets all of the block numbers. Renumber the blocks
962/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000963void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000964 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000965 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000966
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000967 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000968 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000969 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000970
971 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000972 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000973 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000974 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
975 CompareMBBNumbers);
976 WaterList.insert(IP, NewBB);
977}
978
979
980/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000981/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000982/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000983MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000984 MachineBasicBlock *OrigBB = MI->getParent();
985
986 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000987 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000988 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000989 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000990 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000991
Evan Cheng10043e22007-01-19 07:51:42 +0000992 // Splice the instructions starting with MI over to NewBB.
993 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000994
Evan Cheng10043e22007-01-19 07:51:42 +0000995 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000996 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000997 // There doesn't seem to be meaningful DebugInfo available; this doesn't
998 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000999 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +00001000 if (!isThumb)
1001 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
1002 else
1003 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
1004 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001005 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001006
Evan Cheng10043e22007-01-19 07:51:42 +00001007 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +00001008 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001009
Evan Cheng10043e22007-01-19 07:51:42 +00001010 // OrigBB branches to NewBB.
1011 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001012
Evan Cheng10043e22007-01-19 07:51:42 +00001013 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001014 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +00001015 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001016 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001017
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001018 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +00001019 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001020 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +00001021
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001022 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +00001023 // available water after it (but not if it's already there, which happens
1024 // when splitting before a conditional branch that is followed by an
1025 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +00001026 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +00001027 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
1028 CompareMBBNumbers);
1029 MachineBasicBlock* WaterBB = *IP;
1030 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001031 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001032 else
1033 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001034 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001035
Dale Johannesenc17dd572010-07-23 22:50:23 +00001036 // Figure out how large the OrigBB is. As the first half of the original
1037 // block, it cannot contain a tablejump. The size includes
1038 // the new jump we added. (It should be possible to do this without
1039 // recounting everything, but it's very confusing, and this is rarely
1040 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001041 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +00001042
Dale Johannesenc17dd572010-07-23 22:50:23 +00001043 // Figure out how large the NewMBB is. As the second half of the original
1044 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001045 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +00001046
Dale Johannesen01ee5752007-02-25 00:47:03 +00001047 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001048 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +00001049
1050 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +00001051}
1052
Jim Grosbach190e7b62012-03-23 23:07:03 +00001053/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001054/// displacement computation. Update U.KnownAlignment to match its current
1055/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001056unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
1057 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001058 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
1059 unsigned KnownBits = BBI.internalKnownBits();
1060
1061 // The value read from PC is offset from the actual instruction address.
1062 UserOffset += (isThumb ? 4 : 8);
1063
1064 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
1065 // Make sure U.getMaxDisp() returns a constrained range.
1066 U.KnownAlignment = (KnownBits >= 2);
1067
1068 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
1069 // purposes of the displacement computation; compensate for that here.
1070 // For unknown alignments, getMaxDisp() constrains the range instead.
1071 if (isThumb && U.KnownAlignment)
1072 UserOffset &= ~3u;
1073
1074 return UserOffset;
1075}
1076
Jim Grosbach190e7b62012-03-23 23:07:03 +00001077/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001078/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001079/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001080/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001081/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1082/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001083bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001084 unsigned TrialOffset, unsigned MaxDisp,
1085 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001086 if (UserOffset <= TrialOffset) {
1087 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001088 if (TrialOffset - UserOffset <= MaxDisp)
1089 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001090 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001091 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001092 if (UserOffset - TrialOffset <= MaxDisp)
1093 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001094 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001095 }
1096 return false;
1097}
1098
Jim Grosbach190e7b62012-03-23 23:07:03 +00001099/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001100/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001101///
1102/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001103bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001104 MachineBasicBlock* Water, CPUser &U,
1105 unsigned &Growth) {
1106 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1107 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1108 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001109 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001110 if (++NextBlock == MF->end()) {
1111 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1112 NextBlockAlignment = 0;
1113 } else {
1114 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1115 NextBlockAlignment = NextBlock->getAlignment();
1116 }
1117 unsigned Size = U.CPEMI->getOperand(2).getImm();
1118 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001119
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001120 // The CPE may be able to hide in the alignment padding before the next
1121 // block. It may also cause more padding to be required if it is more aligned
1122 // that the next block.
1123 if (CPEEnd > NextBlockOffset) {
1124 Growth = CPEEnd - NextBlockOffset;
1125 // Compute the padding that would go at the end of the CPE to align the next
1126 // block.
1127 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1128
1129 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001130 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001131 // in blocks between CPE and the user.
1132 if (CPEOffset < UserOffset)
1133 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1134 } else
1135 // CPE fits in existing padding.
1136 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001137
Jim Grosbach190e7b62012-03-23 23:07:03 +00001138 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001139}
1140
Jim Grosbach190e7b62012-03-23 23:07:03 +00001141/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001142/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001143bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001144 MachineInstr *CPEMI, unsigned MaxDisp,
1145 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001146 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001147
Dale Johannesene18b13b2007-02-23 05:02:36 +00001148 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001149 DEBUG({
1150 unsigned Block = MI->getParent()->getNumber();
1151 const BasicBlockInfo &BBI = BBInfo[Block];
1152 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1153 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001154 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001155 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001156 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1157 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1158 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001159 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001160 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001161
Jim Grosbach190e7b62012-03-23 23:07:03 +00001162 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001163}
1164
Evan Chenge4510972009-01-28 00:53:34 +00001165#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001166/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1167/// unconditionally branches to its only successor.
1168static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1169 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1170 return false;
1171
1172 MachineBasicBlock *Succ = *MBB->succ_begin();
1173 MachineBasicBlock *Pred = *MBB->pred_begin();
1174 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001175 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1176 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001177 return PredMI->getOperand(0).getMBB() == Succ;
1178 return false;
1179}
Evan Chenge4510972009-01-28 00:53:34 +00001180#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001181
Jim Grosbach190e7b62012-03-23 23:07:03 +00001182void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001183 unsigned BBNum = BB->getNumber();
1184 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001185 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001186 // Include the alignment of the current block.
1187 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1188 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1189 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001190
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001191 // This is where block i begins. Stop if the offset is already correct,
1192 // and we have updated 2 blocks. This is the maximum number of blocks
1193 // changed before calling this function.
1194 if (i > BBNum + 2 &&
1195 BBInfo[i].Offset == Offset &&
1196 BBInfo[i].KnownBits == KnownBits)
1197 break;
1198
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001199 BBInfo[i].Offset = Offset;
1200 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001201 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001202}
1203
Jim Grosbach190e7b62012-03-23 23:07:03 +00001204/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001205/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001206/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001207/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001208
Jim Grosbach190e7b62012-03-23 23:07:03 +00001209bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1210 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001211 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001212 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1213 assert(CPE && "Unexpected!");
1214 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001215 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001216 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001217 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001218 return true;
1219 }
1220 return false;
1221}
1222
Tim Northovera603c402015-05-31 19:22:07 +00001223unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1224 if (CPEMI->getOperand(1).isCPI())
1225 return CPEMI->getOperand(1).getIndex();
1226
1227 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1228}
1229
Dale Johannesene18b13b2007-02-23 05:02:36 +00001230/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1231/// if not, see if an in-range clone of the CPE is in range, and if so,
1232/// change the data structures so the user references the clone. Returns:
1233/// 0 = no existing entry found
1234/// 1 = entry found, and there were no code insertions or deletions
1235/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001236int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001237{
1238 MachineInstr *UserMI = U.MI;
1239 MachineInstr *CPEMI = U.CPEMI;
1240
1241 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001242 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1243 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001244 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001245 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001246 }
1247
Dale Johannesene18b13b2007-02-23 05:02:36 +00001248 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001249 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001250 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1251 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1252 // We already tried this one
1253 if (CPEs[i].CPEMI == CPEMI)
1254 continue;
1255 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001256 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001257 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001258 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001259 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001260 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001261 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001262 // Point the CPUser node to the replacement
1263 U.CPEMI = CPEs[i].CPEMI;
1264 // Change the CPI in the instruction operand to refer to the clone.
1265 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001266 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001267 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001268 break;
1269 }
1270 // Adjust the refcount of the clone...
1271 CPEs[i].RefCount++;
1272 // ...and the original. If we didn't remove the old entry, none of the
1273 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001274 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001275 }
1276 }
1277 return 0;
1278}
1279
Dale Johannesen440995b2007-02-28 18:41:23 +00001280/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1281/// the specific unconditional branch instruction.
1282static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001283 switch (Opc) {
1284 case ARM::tB:
1285 return ((1<<10)-1)*2;
1286 case ARM::t2B:
1287 return ((1<<23)-1)*2;
1288 default:
1289 break;
1290 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001291
David Goodwin27303cd2009-06-30 18:04:13 +00001292 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001293}
1294
Jim Grosbach190e7b62012-03-23 23:07:03 +00001295/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001296/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001297/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001298/// is set to the WaterList entry. For Thumb, prefer water that will not
1299/// introduce padding to water that will. To ensure that this pass
1300/// terminates, the CPE location for a particular CPUser is only allowed to
1301/// move to a lower address, so search backward from the end of the list and
1302/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001303bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001304 water_iterator &WaterIter,
1305 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001306 if (WaterList.empty())
1307 return false;
1308
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001309 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001310 // The nearest water without splitting the UserBB is right after it.
1311 // If the distance is still large (we have a big BB), then we need to split it
1312 // if we don't converge after certain iterations. This helps the following
1313 // situation to converge:
1314 // BB0:
1315 // Big BB
1316 // BB1:
1317 // Constant Pool
1318 // When a CP access is out of range, BB0 may be used as water. However,
1319 // inserting islands between BB0 and BB1 makes other accesses out of range.
1320 MachineBasicBlock *UserBB = U.MI->getParent();
1321 unsigned MinNoSplitDisp =
1322 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1323 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1324 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001325 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001326 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001327 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001328 // Check if water is in range and is either at a lower address than the
1329 // current "high water mark" or a new water block that was created since
1330 // the previous iteration by inserting an unconditional branch. In the
1331 // latter case, we want to allow resetting the high water mark back to
1332 // this new water since we haven't seen it before. Inserting branches
1333 // should be relatively uncommon and when it does happen, we want to be
1334 // sure to take advantage of it for all the CPEs near that block, so that
1335 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001336 // When CloserWater is true, we try to find the lowest address after (or
1337 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001338 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001339 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001340 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001341 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1342 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001343 // This is the least amount of required padding seen so far.
1344 BestGrowth = Growth;
1345 WaterIter = IP;
1346 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1347 << " Growth=" << Growth << '\n');
1348
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001349 if (CloserWater && WaterBB == U.MI->getParent())
1350 return true;
1351 // Keep looking unless it is perfect and we're not looking for the lowest
1352 // possible address.
1353 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001354 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001355 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001356 if (IP == B)
1357 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001358 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001359 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001360}
1361
Jim Grosbach190e7b62012-03-23 23:07:03 +00001362/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001363/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1364/// block is used if in range, and the conditional branch munged so control
1365/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001366/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001367/// block following which the new island can be inserted (the WaterList
1368/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001369void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001370 unsigned UserOffset,
1371 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001372 CPUser &U = CPUsers[CPUserIndex];
1373 MachineInstr *UserMI = U.MI;
1374 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001375 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001376 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001377 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001378
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001379 // If the block does not end in an unconditional branch already, and if the
1380 // end of the block is within range, make new water there. (The addition
1381 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001382 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001383 if (BBHasFallthrough(UserMBB)) {
1384 // Size of branch to insert.
1385 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001386 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001387 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001388
Jim Grosbach190e7b62012-03-23 23:07:03 +00001389 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001390 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1391 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001392 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001393 // Add an unconditional branch from UserMBB to fallthrough block. Record
1394 // it for branch lengthening; this new branch will not get out of range,
1395 // but if the preceding conditional branch is out of range, the targets
1396 // will be exchanged, and the altered branch may be out of range, so the
1397 // machinery has to know about it.
1398 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1399 if (!isThumb)
1400 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1401 else
1402 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1403 .addImm(ARMCC::AL).addReg(0);
1404 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1405 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1406 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001407 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001408 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001409 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001410 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001411 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001412
1413 // What a big block. Find a place within the block to split it. This is a
1414 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1415 // entries are 4 bytes: if instruction I references island CPE, and
1416 // instruction I+1 references CPE', it will not work well to put CPE as far
1417 // forward as possible, since then CPE' cannot immediately follow it (that
1418 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1419 // need to create a new island. So, we make a first guess, then walk through
1420 // the instructions between the one currently being looked at and the
1421 // possible insertion point, and make sure any other instructions that
1422 // reference CPEs will be able to use the same island area; if not, we back
1423 // up the insertion point.
1424
1425 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001426 // point where we can add a 4-byte branch instruction, and then align to
1427 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001428 unsigned LogAlign = MF->getAlignment();
1429 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1430 unsigned KnownBits = UserBBI.internalKnownBits();
1431 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001432 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001433 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1434 BaseInsertOffset));
1435
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001436 // The 4 in the following is for the unconditional branch we'll be inserting
1437 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001438 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001439 BaseInsertOffset -= 4;
1440
1441 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1442 << " la=" << LogAlign
1443 << " kb=" << KnownBits
1444 << " up=" << UPad << '\n');
1445
1446 // This could point off the end of the block if we've already got constant
1447 // pool entries following this block; only the last one is in the water list.
1448 // Back past any possible branches (allow for a conditional and a maximally
1449 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001450 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001451 // Ensure BaseInsertOffset is larger than the offset of the instruction
1452 // following UserMI so that the loop which searches for the split point
1453 // iterates at least once.
1454 BaseInsertOffset =
1455 std::max(UserBBI.postOffset() - UPad - 8,
1456 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001457 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1458 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001459 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001460 CPEMI->getOperand(2).getImm();
1461 MachineBasicBlock::iterator MI = UserMI;
1462 ++MI;
1463 unsigned CPUIndex = CPUserIndex+1;
1464 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001465 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001466 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1467 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001468 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001469 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001470 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1471 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001472 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001473 // Shift intertion point by one unit of alignment so it is within reach.
1474 BaseInsertOffset -= 1u << LogAlign;
1475 EndInsertOffset -= 1u << LogAlign;
1476 }
1477 // This is overly conservative, as we don't account for CPEMIs being
1478 // reused within the block, but it doesn't matter much. Also assume CPEs
1479 // are added in order with alignment padding. We may eventually be able
1480 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001481 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001482 CPUIndex++;
1483 }
1484
1485 // Remember the last IT instruction.
1486 if (MI->getOpcode() == ARM::t2IT)
1487 LastIT = MI;
1488 }
1489
1490 --MI;
1491
1492 // Avoid splitting an IT block.
1493 if (LastIT) {
1494 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001495 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001496 if (CC != ARMCC::AL)
1497 MI = LastIT;
1498 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001499
1500 // We really must not split an IT block.
1501 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001502 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001503
Jim Grosbach190e7b62012-03-23 23:07:03 +00001504 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001505}
1506
Jim Grosbach190e7b62012-03-23 23:07:03 +00001507/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001508/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001509/// place in-range. Return true if we changed any addresses (thus must run
1510/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001511bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1512 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001513 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001514 MachineInstr *UserMI = U.MI;
1515 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001516 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001517 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001518 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001519 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001520
Dale Johannesene18b13b2007-02-23 05:02:36 +00001521 // See if the current entry is within range, or there is a clone of it
1522 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001523 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001524 if (result==1) return false;
1525 else if (result==2) return true;
1526
1527 // No existing clone of this CPE is within range.
1528 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001529 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001530
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001531 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001532 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001533 MachineBasicBlock *NewMBB;
1534 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001535 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001536 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001537 MachineBasicBlock *WaterBB = *IP;
1538
1539 // If the original WaterList entry was "new water" on this iteration,
1540 // propagate that to the new island. This is just keeping NewWaterList
1541 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001542 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001543 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001544
Bob Wilson2f9be502009-10-15 20:49:47 +00001545 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001546 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001547 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001548 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001549 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001550 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001551
Jim Grosbach190e7b62012-03-23 23:07:03 +00001552 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001553 // called while handling branches so that the water will be seen on the
1554 // next iteration for constant pools, but in this context, we don't want
1555 // it. Check for this so it will be removed from the WaterList.
1556 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001557 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001558 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1559 if (IP != WaterList.end())
1560 NewWaterList.erase(WaterBB);
1561
1562 // We are adding new water. Update NewWaterList.
1563 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001564 }
1565
Bob Wilson2f9be502009-10-15 20:49:47 +00001566 // Remove the original WaterList entry; we want subsequent insertions in
1567 // this vicinity to go after the one we're about to insert. This
1568 // considerably reduces the number of times we have to move the same CPE
1569 // more than once and is also important to ensure the algorithm terminates.
1570 if (IP != WaterList.end())
1571 WaterList.erase(IP);
1572
Dale Johannesene18b13b2007-02-23 05:02:36 +00001573 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001574 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001575
1576 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001577 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001578
Dale Johannesene18b13b2007-02-23 05:02:36 +00001579 // Now that we have an island to add the CPE to, clone the original CPE and
1580 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001581 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001582 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1583 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001584 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001585 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001586
Tim Northovera603c402015-05-31 19:22:07 +00001587 // Decrement the old entry, and remove it if refcount becomes 0.
1588 decrementCPEReferenceCount(CPI, CPEMI);
1589
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001590 // Mark the basic block as aligned as required by the const-pool entry.
1591 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001592
Evan Cheng10043e22007-01-19 07:51:42 +00001593 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001594 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001595 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001596
Evan Cheng10043e22007-01-19 07:51:42 +00001597 // Finally, change the CPI in the instruction operand to be ID.
1598 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001599 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001600 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001601 break;
1602 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001603
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001604 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001605 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001606
Evan Cheng10043e22007-01-19 07:51:42 +00001607 return true;
1608}
1609
Jim Grosbach190e7b62012-03-23 23:07:03 +00001610/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001611/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001612void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001613 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001614 unsigned Size = CPEMI->getOperand(2).getImm();
1615 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001616 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001617 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001618 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001619 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001620
Evan Chengab28b9a2013-02-21 18:37:54 +00001621 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001622 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001623 } else
1624 // Entries are sorted by descending alignment, so realign from the front.
1625 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1626
Jim Grosbach190e7b62012-03-23 23:07:03 +00001627 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001628 // An island has only one predecessor BB and one successor BB. Check if
1629 // this BB's predecessor jumps directly to this BB's successor. This
1630 // shouldn't happen currently.
1631 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1632 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001633}
1634
Jim Grosbach190e7b62012-03-23 23:07:03 +00001635/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001636/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001637bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001638 unsigned MadeChange = false;
1639 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1640 std::vector<CPEntry> &CPEs = CPEntries[i];
1641 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1642 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001643 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001644 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001645 MadeChange = true;
1646 }
1647 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001648 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001649 return MadeChange;
1650}
1651
Jim Grosbach190e7b62012-03-23 23:07:03 +00001652/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001653/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001654bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001655 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001656 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001657 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001658 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001659
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001660 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001661 << " from BB#" << MI->getParent()->getNumber()
1662 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001663 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001664 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001665
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001666 if (BrOffset <= DestOffset) {
1667 // Branch before the Dest.
1668 if (DestOffset-BrOffset <= MaxDisp)
1669 return true;
1670 } else {
1671 if (BrOffset-DestOffset <= MaxDisp)
1672 return true;
1673 }
1674 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001675}
1676
Jim Grosbach190e7b62012-03-23 23:07:03 +00001677/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001678/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001679bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001680 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001681 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001682
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001683 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001684 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001685 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001686
Evan Cheng7fa69642007-01-30 01:18:38 +00001687 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001688 return fixupUnconditionalBr(Br);
1689 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001690}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001691
Jim Grosbach190e7b62012-03-23 23:07:03 +00001692/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001693/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001694/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001695/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001696bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001697ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001698 MachineInstr *MI = Br.MI;
1699 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001700 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001701 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001702
1703 // Use BL to implement far jump.
1704 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001705 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001706 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001707 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001708 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001709 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001710
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001711 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001712
Evan Cheng7fa69642007-01-30 01:18:38 +00001713 return true;
1714}
1715
Jim Grosbach190e7b62012-03-23 23:07:03 +00001716/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001717/// far away to fit in its displacement field. It is converted to an inverse
1718/// conditional branch + an unconditional branch to the destination.
1719bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001720ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001721 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001722 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001723
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001724 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001725 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001726 // blt L1
1727 // =>
1728 // bge L2
1729 // b L1
1730 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001731 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001732 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001733 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001734
1735 // If the branch is at the end of its MBB and that has a fall-through block,
1736 // direct the updated conditional branch to the fall-through block. Otherwise,
1737 // split the MBB before the next instruction.
1738 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001739 MachineInstr *BMI = &MBB->back();
1740 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001741
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001742 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001743 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001744 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001745 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001746 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001747 // condition and swap destinations:
1748 // beq L1
1749 // b L2
1750 // =>
1751 // bne L2
1752 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001753 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001754 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001755 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001756 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001757 BMI->getOperand(0).setMBB(DestBB);
1758 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001759 MI->getOperand(1).setImm(CC);
1760 return true;
1761 }
1762 }
1763 }
1764
1765 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001766 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001767 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001768 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001769 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001770 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001771 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001772 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001773 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001774 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001775
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001776 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001777 << " also invert condition and change dest. to BB#"
1778 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001779
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001780 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001781 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001782 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001783 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001784 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001785 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001786 if (isThumb)
1787 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1788 .addImm(ARMCC::AL).addReg(0);
1789 else
1790 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001791 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001792 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001793 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001794
1795 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001796 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001797 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001798 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001799 return true;
1800}
Evan Cheng7fa69642007-01-30 01:18:38 +00001801
Jim Grosbach190e7b62012-03-23 23:07:03 +00001802/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001803/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1804/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001805bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001806 bool MadeChange = false;
1807 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1808 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001809 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001810 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001811 MI->getOperand(2).getReg() == ARM::PC &&
1812 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001813 // Create the new insn and copy the predicate from the old.
1814 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1815 .addOperand(MI->getOperand(0))
1816 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001817 MI->eraseFromParent();
1818 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001819 }
1820 }
1821 return MadeChange;
1822}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001823
Jim Grosbach190e7b62012-03-23 23:07:03 +00001824// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001825// below may shrink MI.
1826bool
1827ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1828 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001829 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001830 case ARM::t2LEApcrel:
1831 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001832 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001833 case ARM::t2B:
1834 case ARM::t2Bcc:
1835 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001836 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001837 case ARM::t2BR_JT:
1838 return true;
1839 }
1840 return false;
1841}
1842
Jim Grosbach190e7b62012-03-23 23:07:03 +00001843bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001844 bool MadeChange = false;
1845
1846 // Shrink ADR and LDR from constantpool.
1847 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1848 CPUser &U = CPUsers[i];
1849 unsigned Opcode = U.MI->getOpcode();
1850 unsigned NewOpc = 0;
1851 unsigned Scale = 1;
1852 unsigned Bits = 0;
1853 switch (Opcode) {
1854 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001855 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001856 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1857 NewOpc = ARM::tLEApcrel;
1858 Bits = 8;
1859 Scale = 4;
1860 }
1861 break;
1862 case ARM::t2LDRpci:
1863 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1864 NewOpc = ARM::tLDRpci;
1865 Bits = 8;
1866 Scale = 4;
1867 }
1868 break;
1869 }
1870
1871 if (!NewOpc)
1872 continue;
1873
Jim Grosbach190e7b62012-03-23 23:07:03 +00001874 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001875 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001876
1877 // Be conservative with inline asm.
1878 if (!U.KnownAlignment)
1879 MaxOffs -= 2;
1880
Evan Chengdb73d682009-08-14 00:32:16 +00001881 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001882 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001883 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001884 U.MI->setDesc(TII->get(NewOpc));
1885 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001886 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001887 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001888 ++NumT2CPShrunk;
1889 MadeChange = true;
1890 }
1891 }
1892
Evan Chengdb73d682009-08-14 00:32:16 +00001893 return MadeChange;
1894}
1895
Jim Grosbach190e7b62012-03-23 23:07:03 +00001896bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001897 bool MadeChange = false;
1898
Peter Collingbourne167668f2015-04-23 20:31:35 +00001899 // The order in which branches appear in ImmBranches is approximately their
1900 // order within the function body. By visiting later branches first, we reduce
1901 // the distance between earlier forward branches and their targets, making it
1902 // more likely that the cbn?z optimization, which can only apply to forward
1903 // branches, will succeed.
1904 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1905 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001906 unsigned Opcode = Br.MI->getOpcode();
1907 unsigned NewOpc = 0;
1908 unsigned Scale = 1;
1909 unsigned Bits = 0;
1910 switch (Opcode) {
1911 default: break;
1912 case ARM::t2B:
1913 NewOpc = ARM::tB;
1914 Bits = 11;
1915 Scale = 2;
1916 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001917 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001918 NewOpc = ARM::tBcc;
1919 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001920 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001921 break;
1922 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001923 }
1924 if (NewOpc) {
1925 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1926 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001927 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001928 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001929 Br.MI->setDesc(TII->get(NewOpc));
1930 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001931 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001932 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001933 ++NumT2BrShrunk;
1934 MadeChange = true;
1935 }
1936 }
1937
1938 Opcode = Br.MI->getOpcode();
1939 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001940 continue;
1941
Evan Cheng6bb95252012-01-14 01:53:46 +00001942 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1943 // so this transformation is not safe.
1944 if (!Br.MI->killsRegister(ARM::CPSR))
1945 continue;
1946
Evan Cheng6f29ad92009-10-31 23:46:45 +00001947 NewOpc = 0;
1948 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001949 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001950 if (Pred == ARMCC::EQ)
1951 NewOpc = ARM::tCBZ;
1952 else if (Pred == ARMCC::NE)
1953 NewOpc = ARM::tCBNZ;
1954 if (!NewOpc)
1955 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001956 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001957 // Check if the distance is within 126. Subtract starting offset by 2
1958 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001959 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001960 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001961 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001962 MachineBasicBlock::iterator CmpMI = Br.MI;
1963 if (CmpMI != Br.MI->getParent()->begin()) {
1964 --CmpMI;
1965 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1966 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001967 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001968 if (Pred == ARMCC::AL &&
1969 CmpMI->getOperand(1).getImm() == 0 &&
1970 isARMLowRegister(Reg)) {
1971 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001972 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001973 MachineInstr *NewBR =
1974 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1975 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1976 CmpMI->eraseFromParent();
1977 Br.MI->eraseFromParent();
1978 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001979 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001980 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001981 ++NumCBZ;
1982 MadeChange = true;
1983 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001984 }
1985 }
Evan Chenge41903b2009-08-14 18:31:44 +00001986 }
1987 }
1988
1989 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001990}
1991
Tim Northovera603c402015-05-31 19:22:07 +00001992static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1993 unsigned BaseReg) {
1994 if (I.getOpcode() != ARM::t2ADDrs)
1995 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001996
Tim Northovera603c402015-05-31 19:22:07 +00001997 if (I.getOperand(0).getReg() != EntryReg)
1998 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001999
Tim Northovera603c402015-05-31 19:22:07 +00002000 if (I.getOperand(1).getReg() != BaseReg)
2001 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002002
Tim Northovera603c402015-05-31 19:22:07 +00002003 // FIXME: what about CC and IdxReg?
2004 return true;
2005}
Tim Northover688f7bb2015-05-13 20:28:32 +00002006
Tim Northovera603c402015-05-31 19:22:07 +00002007/// \brief While trying to form a TBB/TBH instruction, we may (if the table
2008/// doesn't immediately follow the BR_JT) need access to the start of the
2009/// jump-table. We know one instruction that produces such a register; this
2010/// function works out whether that definition can be preserved to the BR_JT,
2011/// possibly by removing an intervening addition (which is usually needed to
2012/// calculate the actual entry to jump to).
2013bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
2014 MachineInstr *LEAMI,
2015 unsigned &DeadSize,
2016 bool &CanDeleteLEA,
2017 bool &BaseRegKill) {
2018 if (JumpMI->getParent() != LEAMI->getParent())
2019 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002020
Tim Northovera603c402015-05-31 19:22:07 +00002021 // Now we hope that we have at least these instructions in the basic block:
2022 // BaseReg = t2LEA ...
2023 // [...]
2024 // EntryReg = t2ADDrs BaseReg, ...
2025 // [...]
2026 // t2BR_JT EntryReg
2027 //
2028 // We have to be very conservative about what we recognise here though. The
2029 // main perturbing factors to watch out for are:
2030 // + Spills at any point in the chain: not direct problems but we would
2031 // expect a blocking Def of the spilled register so in practice what we
2032 // can do is limited.
2033 // + EntryReg == BaseReg: this is the one situation we should allow a Def
2034 // of BaseReg, but only if the t2ADDrs can be removed.
2035 // + Some instruction other than t2ADDrs computing the entry. Not seen in
2036 // the wild, but we should be careful.
2037 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2038 unsigned BaseReg = LEAMI->getOperand(0).getReg();
2039
2040 CanDeleteLEA = true;
2041 BaseRegKill = false;
2042 MachineInstr *RemovableAdd = nullptr;
2043 MachineBasicBlock::iterator I(LEAMI);
2044 for (++I; &*I != JumpMI; ++I) {
2045 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2046 RemovableAdd = &*I;
2047 break;
2048 }
2049
2050 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2051 const MachineOperand &MO = I->getOperand(K);
2052 if (!MO.isReg() || !MO.getReg())
2053 continue;
2054 if (MO.isDef() && MO.getReg() == BaseReg)
2055 return false;
2056 if (MO.isUse() && MO.getReg() == BaseReg) {
2057 BaseRegKill = BaseRegKill || MO.isKill();
2058 CanDeleteLEA = false;
2059 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002060 }
2061 }
2062
Tim Northovera603c402015-05-31 19:22:07 +00002063 if (!RemovableAdd)
2064 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00002065
Tim Northovera603c402015-05-31 19:22:07 +00002066 // Check the add really is removable, and that nothing else in the block
2067 // clobbers BaseReg.
2068 for (++I; &*I != JumpMI; ++I) {
2069 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2070 const MachineOperand &MO = I->getOperand(K);
2071 if (!MO.isReg() || !MO.getReg())
2072 continue;
2073 if (MO.isDef() && MO.getReg() == BaseReg)
2074 return false;
2075 if (MO.isUse() && MO.getReg() == EntryReg)
2076 RemovableAdd = nullptr;
2077 }
2078 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002079
Tim Northovera603c402015-05-31 19:22:07 +00002080 if (RemovableAdd) {
2081 RemovableAdd->eraseFromParent();
2082 DeadSize += 4;
2083 } else if (BaseReg == EntryReg) {
2084 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2085 // preserve it.
2086 return false;
2087 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002088
Tim Northovera603c402015-05-31 19:22:07 +00002089 // We reached the end of the block without seeing another definition of
2090 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2091 // used in the TBB/TBH if necessary.
2092 return true;
2093}
Tim Northover688f7bb2015-05-13 20:28:32 +00002094
Tim Northovera603c402015-05-31 19:22:07 +00002095/// \brief Returns whether CPEMI is the first instruction in the block
2096/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2097/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002098/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002099static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002100 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002101 MachineFunction *MF = MBB->getParent();
2102 ++MBB;
2103
2104 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2105 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002106}
2107
Jim Grosbach190e7b62012-03-23 23:07:03 +00002108/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002109/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002110bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002111 bool MadeChange = false;
2112
2113 // FIXME: After the tables are shrunk, can we get rid some of the
2114 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002115 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002116 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002117
Evan Chengc6d70ae2009-07-29 02:18:14 +00002118 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2119 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2120 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002121 const MCInstrDesc &MCID = MI->getDesc();
2122 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002123 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002124 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2125 unsigned JTI = JTOP.getIndex();
2126 assert(JTI < JT.size());
2127
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002128 bool ByteOk = true;
2129 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002130 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002131 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002132 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2133 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002134 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002135 // Negative offset is not ok. FIXME: We should change BB layout to make
2136 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002137 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002138 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002139 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002140 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002141 HalfWordOk = false;
2142 if (!ByteOk && !HalfWordOk)
2143 break;
2144 }
2145
Tim Northovera603c402015-05-31 19:22:07 +00002146 if (!ByteOk && !HalfWordOk)
2147 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002148
Tim Northovera603c402015-05-31 19:22:07 +00002149 MachineBasicBlock *MBB = MI->getParent();
2150 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2151 continue;
2152 unsigned IdxReg = MI->getOperand(1).getReg();
2153 bool IdxRegKill = MI->getOperand(1).isKill();
2154
2155 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2156 unsigned DeadSize = 0;
2157 bool CanDeleteLEA = false;
2158 bool BaseRegKill = false;
2159 bool PreservedBaseReg =
2160 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2161
2162 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2163 continue;
2164
2165 DEBUG(dbgs() << "Shrink JT: " << *MI);
2166 MachineInstr *CPEMI = User.CPEMI;
2167 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2168 MachineBasicBlock::iterator MI_JT = MI;
2169 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002170 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002171 .addReg(User.MI->getOperand(0).getReg(),
2172 getKillRegState(BaseRegKill))
2173 .addReg(IdxReg, getKillRegState(IdxRegKill))
2174 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2175 .addImm(CPEMI->getOperand(0).getImm());
2176 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002177
Tim Northovera603c402015-05-31 19:22:07 +00002178 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2179 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002180
Tim Northovera603c402015-05-31 19:22:07 +00002181 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2182 NewJTMI->getOperand(0).setReg(ARM::PC);
2183 NewJTMI->getOperand(0).setIsKill(false);
2184
2185 if (CanDeleteLEA) {
2186 User.MI->eraseFromParent();
2187 DeadSize += 4;
2188
2189 // The LEA was eliminated, the TBB instruction becomes the only new user
2190 // of the jump table.
2191 User.MI = NewJTMI;
2192 User.MaxDisp = 4;
2193 User.NegOk = false;
2194 User.IsSoImm = false;
2195 User.KnownAlignment = false;
2196 } else {
2197 // The LEA couldn't be eliminated, so we must add another CPUser to
2198 // record the TBB or TBH use.
2199 int CPEntryIdx = JumpTableEntryIndices[JTI];
2200 auto &CPEs = CPEntries[CPEntryIdx];
2201 auto Entry = std::find_if(CPEs.begin(), CPEs.end(), [&](CPEntry &E) {
2202 return E.CPEMI == User.CPEMI;
2203 });
2204 ++Entry->RefCount;
2205 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2206 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002207 }
Tim Northovera603c402015-05-31 19:22:07 +00002208
2209 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
2210 unsigned OrigSize = TII->GetInstSizeInBytes(MI);
2211 MI->eraseFromParent();
2212
2213 int Delta = OrigSize - NewSize + DeadSize;
2214 BBInfo[MBB->getNumber()].Size -= Delta;
2215 adjustBBOffsetsAfter(MBB);
2216
2217 ++NumTBs;
2218 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002219 }
2220
2221 return MadeChange;
2222}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002223
Jim Grosbach190e7b62012-03-23 23:07:03 +00002224/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002225/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002226bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002227 bool MadeChange = false;
2228
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002229 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002230 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002231
Jim Grosbach5d577142009-11-12 17:25:07 +00002232 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2233 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2234 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002235 const MCInstrDesc &MCID = MI->getDesc();
2236 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002237 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002238 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2239 unsigned JTI = JTOP.getIndex();
2240 assert(JTI < JT.size());
2241
2242 // We prefer if target blocks for the jump table come after the jump
2243 // instruction so we can use TB[BH]. Loop through the target blocks
2244 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002245 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002246 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2247 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2248 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002249 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002250
Jim Grosbach9785e592009-11-16 18:58:52 +00002251 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002252 // The destination precedes the switch. Try to move the block forward
2253 // so we have a positive offset.
2254 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002255 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002256 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002257 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002258 MadeChange = true;
2259 }
2260 }
2261 }
2262
2263 return MadeChange;
2264}
2265
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002266MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002267adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002268 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002269 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002270 // table that branches back to the actual target. This is a very simple
2271 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002272 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002273 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002274 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002275 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002276 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002277
Jim Grosbach47d5e332009-11-16 17:10:56 +00002278 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002279 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002280
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002281 // If the block ends in an unconditional branch, move it. The prior block
2282 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002283 // and make sure we're not trying to move the entry block of the function.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002284 if (!B && Cond.empty() && BB != &MF->front() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002285 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002286 BB->moveAfter(JTBB);
2287 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002288 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002289 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002290 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002291 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002292 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002293 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002294
2295 // Create a new MBB for the code after the jump BB.
2296 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002297 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002298 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002299 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002300
2301 // Add an unconditional branch from NewBB to BB.
2302 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2303 // correspond directly to anything in the source.
2304 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002305 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2306 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002307
Jim Grosbach43d21082009-11-14 20:10:18 +00002308 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002309 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002310
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002311 // Update the CFG.
2312 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002313 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002314
Jim Grosbach5d577142009-11-12 17:25:07 +00002315 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002316 return NewBB;
2317}