blob: d01be5c5844880f44af439586b4e903e2bb1e297 [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
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000282 MachineFunctionProperties getRequiredProperties() const override {
283 return MachineFunctionProperties().set(
284 MachineFunctionProperties::Property::AllVRegsAllocated);
285 }
286
Craig Topper6bc27bf2014-03-10 02:09:33 +0000287 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000288 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000289 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000290
Evan Cheng10043e22007-01-19 07:51:42 +0000291 private:
Tim Northovera603c402015-05-31 19:22:07 +0000292 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
293 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000294 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000295 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000296 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000297 void scanFunctionJumpTables();
298 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
299 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
300 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
301 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
302 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000303 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000304 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
305 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000306 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000307 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000308 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000309 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000310 void removeDeadCPEMI(MachineInstr *CPEMI);
311 bool removeUnusedCPEntries();
312 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
313 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
314 bool DoDump = false);
315 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000316 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000317 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
318 bool fixupImmediateBr(ImmBranch &Br);
319 bool fixupConditionalBr(ImmBranch &Br);
320 bool fixupUnconditionalBr(ImmBranch &Br);
321 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000322 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000323 bool optimizeThumb2Instructions();
324 bool optimizeThumb2Branches();
325 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000326 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
327 unsigned &DeadSize, bool &CanDeleteLEA,
328 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000329 bool optimizeThumb2JumpTables();
330 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000331 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000332
Jim Grosbach190e7b62012-03-23 23:07:03 +0000333 void computeBlockSize(MachineBasicBlock *MBB);
334 unsigned getOffsetOf(MachineInstr *MI) const;
335 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000336 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000337 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000338
Jim Grosbach190e7b62012-03-23 23:07:03 +0000339 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000340 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000341 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000342 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000343 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000344 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000345 }
Evan Cheng10043e22007-01-19 07:51:42 +0000346 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000347 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000348}
Evan Cheng10043e22007-01-19 07:51:42 +0000349
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000350/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000351void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000352#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000353 assert(std::is_sorted(MF->begin(), MF->end(),
354 [this](const MachineBasicBlock &LHS,
355 const MachineBasicBlock &RHS) {
356 return BBInfo[LHS.getNumber()].postOffset() <
357 BBInfo[RHS.getNumber()].postOffset();
358 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000359 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000360 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
361 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000362 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000363 // Verify offset using the real max displacement without the safety
364 // adjustment.
365 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000366 /* DoDump = */ true)) {
367 DEBUG(dbgs() << "OK\n");
368 continue;
369 }
370 DEBUG(dbgs() << "Out of range.\n");
371 dumpBBs();
372 DEBUG(MF->dump());
373 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000374 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000375#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000376}
377
378/// print block size and offset information - debugging
379void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000380 DEBUG({
381 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
382 const BasicBlockInfo &BBI = BBInfo[J];
383 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
384 << " kb=" << unsigned(BBI.KnownBits)
385 << " ua=" << unsigned(BBI.Unalign)
386 << " pa=" << unsigned(BBI.PostAlign)
387 << format(" size=%#x\n", BBInfo[J].Size);
388 }
389 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000390}
391
Evan Cheng22c7cf52007-01-25 03:12:46 +0000392/// createARMConstantIslandPass - returns an instance of the constpool
393/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000394FunctionPass *llvm::createARMConstantIslandPass() {
395 return new ARMConstantIslands();
396}
397
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000398bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
399 MF = &mf;
400 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000401
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000402 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000403 << MCP->getConstants().size() << " CP entries, aligned to "
404 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000405
Eric Christopher1b21f002015-01-29 00:19:33 +0000406 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
407 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000408 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000409
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000410 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000411 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000412 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000413
414 HasFarJump = false;
415
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000416 // This pass invalidates liveness information when it splits basic blocks.
417 MF->getRegInfo().invalidateLiveness();
418
Evan Cheng10043e22007-01-19 07:51:42 +0000419 // Renumber all of the machine basic blocks in the function, guaranteeing that
420 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000421 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000422
Jim Grosbach5d577142009-11-12 17:25:07 +0000423 // Try to reorder and otherwise adjust the block layout to make good use
424 // of the TB[BH] instructions.
425 bool MadeChange = false;
426 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000427 scanFunctionJumpTables();
428 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000429 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000430 T2JumpTables.clear();
431 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000432 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000433 }
434
Evan Cheng10043e22007-01-19 07:51:42 +0000435 // Perform the initial placement of the constant pool entries. To start with,
436 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000437 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000438 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000439 doInitialConstPlacement(CPEMIs);
440
441 if (MF->getJumpTableInfo())
442 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000443
Evan Cheng10043e22007-01-19 07:51:42 +0000444 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000445 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000446
Evan Cheng10043e22007-01-19 07:51:42 +0000447 // Do the initial scan of the function, building up information about the
448 // sizes of each block, the location of all the water, and finding all of the
449 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000450 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000451 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000452 DEBUG(dumpBBs());
453
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000454 // Functions with jump tables need an alignment of 4 because they use the ADR
455 // instruction, which aligns the PC to 4 bytes before adding an offset.
456 if (!T2JumpTables.empty())
457 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000458
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000459 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000460 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000461
Evan Cheng7fa69642007-01-30 01:18:38 +0000462 // Iteratively place constant pool entries and fix up branches until there
463 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000464 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000465 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000466 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000467 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000468 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000469 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000470 // If it doesn't end in 10, the input may have huge BB or many CPEs.
471 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000472 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
473 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000474 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000475 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000476
Bob Wilson2f9be502009-10-15 20:49:47 +0000477 // Clear NewWaterList now. If we split a block for branches, it should
478 // appear as "new water" for the next iteration of constant pool placement.
479 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000480
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000481 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000482 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000483 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000484 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000485 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000486 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000487 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000488
489 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000490 break;
491 MadeChange = true;
492 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000493
Bradley Smitha1189102016-01-15 10:26:17 +0000494 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000495 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000496 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000497
Bradley Smitha1189102016-01-15 10:26:17 +0000498 // Shrink 32-bit branch instructions.
499 if (isThumb && STI->hasV8MBaselineOps())
500 MadeChange |= optimizeThumb2Branches();
501
502 // Optimize jump tables using TBB / TBH.
503 if (isThumb2)
504 MadeChange |= optimizeThumb2JumpTables();
505
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000506 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000507 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000508
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000509 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
510 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000511 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000512 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000513
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000514 // Save the mapping between original and cloned constpool entries.
515 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
516 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
517 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000518 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
519 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000520 }
521 }
522
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000523 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000524
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000525 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000526 WaterList.clear();
527 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000528 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000529 JumpTableEntryIndices.clear();
530 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000531 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000532 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000533 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000534
535 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000536}
537
Tim Northovera603c402015-05-31 19:22:07 +0000538/// \brief Perform the initial placement of the regular constant pool entries.
539/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000540void
Tim Northovera603c402015-05-31 19:22:07 +0000541ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000542 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000543 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
544 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000545
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000546 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000547 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000548
549 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000550 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000551
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000552 // The function needs to be as aligned as the basic blocks. The linker may
553 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000554 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000555
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000556 // Order the entries in BB by descending alignment. That ensures correct
557 // alignment of all entries as long as BB is sufficiently aligned. Keep
558 // track of the insertion point for each alignment. We are going to bucket
559 // sort the entries as they are created.
560 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000561
Evan Cheng10043e22007-01-19 07:51:42 +0000562 // Add all of the constants from the constant pool to the end block, use an
563 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000564 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000565
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000566 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000567 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000568 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000569 assert(Size >= 4 && "Too small constant pool entry");
570 unsigned Align = CPs[i].getAlignment();
571 assert(isPowerOf2_32(Align) && "Invalid alignment");
572 // Verify that all constant pool entries are a multiple of their alignment.
573 // If not, we would have to pad them out so that instructions stay aligned.
574 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
575
576 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
577 unsigned LogAlign = Log2_32(Align);
578 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000579 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000580 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000581 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000582 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000583
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000584 // Ensure that future entries with higher alignment get inserted before
585 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000586 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000587 if (InsPoint[a] == InsAt)
588 InsPoint[a] = CPEMI;
589
Evan Cheng8b7700f2007-02-09 20:54:44 +0000590 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000591 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000592 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000593 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
594 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000595 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000596 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000597}
598
Tim Northovera603c402015-05-31 19:22:07 +0000599/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
600/// instructions can be made more efficient if the jump table immediately
601/// follows the instruction, it's best to place them immediately next to their
602/// jumps to begin with. In almost all cases they'll never be moved from that
603/// position.
604void ARMConstantIslands::doInitialJumpTablePlacement(
605 std::vector<MachineInstr *> &CPEMIs) {
606 unsigned i = CPEntries.size();
607 auto MJTI = MF->getJumpTableInfo();
608 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
609
610 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
611 for (MachineBasicBlock &MBB : *MF) {
612 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000613 if (MI == MBB.end())
614 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000615
616 unsigned JTOpcode;
617 switch (MI->getOpcode()) {
618 default:
619 continue;
620 case ARM::BR_JTadd:
621 case ARM::BR_JTr:
622 case ARM::tBR_JTr:
623 case ARM::BR_JTm:
624 JTOpcode = ARM::JUMPTABLE_ADDRS;
625 break;
626 case ARM::t2BR_JT:
627 JTOpcode = ARM::JUMPTABLE_INSTS;
628 break;
629 case ARM::t2TBB_JT:
630 JTOpcode = ARM::JUMPTABLE_TBB;
631 break;
632 case ARM::t2TBH_JT:
633 JTOpcode = ARM::JUMPTABLE_TBH;
634 break;
635 }
636
637 unsigned NumOps = MI->getDesc().getNumOperands();
638 MachineOperand JTOp =
639 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
640 unsigned JTI = JTOp.getIndex();
641 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
642 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
643 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
644 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
645 DebugLoc(), TII->get(JTOpcode))
646 .addImm(i++)
647 .addJumpTableIndex(JTI)
648 .addImm(Size);
649 CPEMIs.push_back(CPEMI);
650 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
651 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
652 if (!LastCorrectlyNumberedBB)
653 LastCorrectlyNumberedBB = &MBB;
654 }
655
656 // If we did anything then we need to renumber the subsequent blocks.
657 if (LastCorrectlyNumberedBB)
658 MF->RenumberBlocks(LastCorrectlyNumberedBB);
659}
660
Dale Johannesene18b13b2007-02-23 05:02:36 +0000661/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000662/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000663bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000664 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000665 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000666 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000667 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000668 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000669
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000670 MachineBasicBlock *NextBB = &*std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000671 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
672 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000673
Tim Northoverab85dcc2014-11-13 17:58:51 +0000674 // Try to analyze the end of the block. A potential fallthrough may already
675 // have an unconditional branch for whatever reason.
676 MachineBasicBlock *TBB, *FBB;
677 SmallVector<MachineOperand, 4> Cond;
678 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
679 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000680}
681
Evan Cheng8b7700f2007-02-09 20:54:44 +0000682/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
683/// look up the corresponding CPEntry.
684ARMConstantIslands::CPEntry
685*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
686 const MachineInstr *CPEMI) {
687 std::vector<CPEntry> &CPEs = CPEntries[CPI];
688 // Number of entries per constpool index should be small, just do a
689 // linear search.
690 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
691 if (CPEs[i].CPEMI == CPEMI)
692 return &CPEs[i];
693 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000694 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000695}
696
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000697/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000698/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000699unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000700 switch (CPEMI->getOpcode()) {
701 case ARM::CONSTPOOL_ENTRY:
702 break;
703 case ARM::JUMPTABLE_TBB:
704 return 0;
705 case ARM::JUMPTABLE_TBH:
706 case ARM::JUMPTABLE_INSTS:
707 return 1;
708 case ARM::JUMPTABLE_ADDRS:
709 return 2;
710 default:
711 llvm_unreachable("unknown constpool entry kind");
712 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000713
Tim Northovera603c402015-05-31 19:22:07 +0000714 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000715 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
716 unsigned Align = MCP->getConstants()[CPI].getAlignment();
717 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
718 return Log2_32(Align);
719}
720
Jim Grosbach190e7b62012-03-23 23:07:03 +0000721/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000722/// information about the sizes of each block and the locations of all
723/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000724void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000725 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000726 MBBI != E; ++MBBI) {
727 MachineBasicBlock &MBB = *MBBI;
728
Jim Grosbach5d577142009-11-12 17:25:07 +0000729 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000730 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000731 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000732 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000733 }
734}
735
Jim Grosbach190e7b62012-03-23 23:07:03 +0000736/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000737/// information about the sizes of each block, the location of all the water,
738/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000739void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000740initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000741 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000742 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000743
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000744 // First thing, compute the size of all basic blocks, and see if the function
745 // has any inline assembly in it. If so, we have to be conservative about
746 // alignment assumptions, as we don't know for sure the size of any
747 // instructions in the inline assembly.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000748 for (MachineBasicBlock &MBB : *MF)
749 computeBlockSize(&MBB);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000750
751 // The known bits of the entry block offset are determined by the function
752 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000753 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000754
755 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000756 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000757
Bill Wendling18581a42010-12-21 01:54:40 +0000758 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000759 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000760 MBBI != E; ++MBBI) {
761 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000762
Evan Cheng10043e22007-01-19 07:51:42 +0000763 // If this block doesn't fall through into the next MBB, then this is
764 // 'water' that a constant pool island could be placed.
765 if (!BBHasFallthrough(&MBB))
766 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000767
Evan Cheng10043e22007-01-19 07:51:42 +0000768 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
769 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000770 if (I->isDebugValue())
771 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000772
Matthias Braunfa3872e2015-05-18 20:27:55 +0000773 unsigned Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000774 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000775 bool isCond = false;
776 unsigned Bits = 0;
777 unsigned Scale = 1;
778 int UOpc = Opc;
779 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000780 default:
781 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000782 case ARM::t2BR_JT:
783 T2JumpTables.push_back(I);
784 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000785 case ARM::Bcc:
786 isCond = true;
787 UOpc = ARM::B;
788 // Fallthrough
789 case ARM::B:
790 Bits = 24;
791 Scale = 4;
792 break;
793 case ARM::tBcc:
794 isCond = true;
795 UOpc = ARM::tB;
796 Bits = 8;
797 Scale = 2;
798 break;
799 case ARM::tB:
800 Bits = 11;
801 Scale = 2;
802 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000803 case ARM::t2Bcc:
804 isCond = true;
805 UOpc = ARM::t2B;
806 Bits = 20;
807 Scale = 2;
808 break;
809 case ARM::t2B:
810 Bits = 24;
811 Scale = 2;
812 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000813 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000814
815 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000816 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000817 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000818 }
819
Evan Cheng7fa69642007-01-30 01:18:38 +0000820 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
821 PushPopMIs.push_back(I);
822
Tim Northovera603c402015-05-31 19:22:07 +0000823 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
824 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
825 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000826 continue;
827
Evan Cheng10043e22007-01-19 07:51:42 +0000828 // Scan the instructions for constant pool operands.
829 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Tim Northovera603c402015-05-31 19:22:07 +0000830 if (I->getOperand(op).isCPI() || I->getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000831 // We found one. The addressing mode tells us the max displacement
832 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000833
Evan Cheng10043e22007-01-19 07:51:42 +0000834 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000835 unsigned Bits = 0;
836 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000837 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000838 bool IsSoImm = false;
839
840 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000841 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000842 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000843
844 // Taking the address of a CP entry.
845 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000846 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000847 // This takes a SoImm, which is 8 bit immediate rotated. We'll
848 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000849 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000850 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000851 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000852 Scale = 4;
853 NegOk = true;
854 IsSoImm = true;
855 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000856 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000857 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000858 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000859 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000860 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000861 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000862 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000863 Bits = 8;
864 Scale = 4;
865 break;
866
David Majnemer452f1f92013-06-04 17:46:15 +0000867 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000868 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000869 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000870 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000871 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000872 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000873 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000874
875 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000876 Bits = 8;
877 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000878 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000879
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000880 case ARM::VLDRD:
881 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000882 Bits = 8;
883 Scale = 4; // +-(offset_8*4)
884 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000885 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000886 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000887
Evan Cheng10043e22007-01-19 07:51:42 +0000888 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000889 unsigned CPI = I->getOperand(op).getIndex();
Tim Northovera603c402015-05-31 19:22:07 +0000890 if (I->getOperand(op).isJTI()) {
891 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
892 CPI = JumpTableEntryIndices[CPI];
893 }
894
Evan Cheng8b7700f2007-02-09 20:54:44 +0000895 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000896 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000897 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000898
899 // Increment corresponding CPEntry reference count.
900 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
901 assert(CPE && "Cannot find a corresponding CPEntry!");
902 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000903
Evan Cheng10043e22007-01-19 07:51:42 +0000904 // Instructions can only use one CP entry, don't bother scanning the
905 // rest of the operands.
906 break;
907 }
908 }
Evan Cheng10043e22007-01-19 07:51:42 +0000909 }
910}
911
Jim Grosbach190e7b62012-03-23 23:07:03 +0000912/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000913/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000914void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000915 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
916 BBI.Size = 0;
917 BBI.Unalign = 0;
918 BBI.PostAlign = 0;
919
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000920 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
921 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000922 BBI.Size += TII->GetInstSizeInBytes(I);
923 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
924 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000925 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000926 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000927 // Also consider instructions that may be shrunk later.
928 else if (isThumb && mayOptimizeThumb2Instruction(I))
929 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000930 }
931
932 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000933 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000934 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000935 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000936 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000937}
938
Jim Grosbach190e7b62012-03-23 23:07:03 +0000939/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000940/// from the start of the function. This offset changes as stuff is moved
941/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000942unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000943 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000944
Evan Cheng10043e22007-01-19 07:51:42 +0000945 // The offset is composed of two things: the sum of the sizes of all MBB's
946 // before this instruction's block, and the offset from the start of the block
947 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000948 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000949
950 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000951 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000952 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000953 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000954 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000955 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000956}
957
958/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
959/// ID.
960static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
961 const MachineBasicBlock *RHS) {
962 return LHS->getNumber() < RHS->getNumber();
963}
964
Jim Grosbach190e7b62012-03-23 23:07:03 +0000965/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000966/// machine function, it upsets all of the block numbers. Renumber the blocks
967/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000968void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000969 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000970 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000971
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000972 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000973 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000974 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000975
976 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000977 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000978 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000979 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
980 CompareMBBNumbers);
981 WaterList.insert(IP, NewBB);
982}
983
984
985/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000986/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000987/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000988MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000989 MachineBasicBlock *OrigBB = MI->getParent();
990
991 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000992 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000993 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000994 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000995 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000996
Evan Cheng10043e22007-01-19 07:51:42 +0000997 // Splice the instructions starting with MI over to NewBB.
998 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000999
Evan Cheng10043e22007-01-19 07:51:42 +00001000 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +00001001 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +00001002 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1003 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +00001004 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +00001005 if (!isThumb)
1006 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
1007 else
1008 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
1009 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001010 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001011
Evan Cheng10043e22007-01-19 07:51:42 +00001012 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +00001013 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001014
Evan Cheng10043e22007-01-19 07:51:42 +00001015 // OrigBB branches to NewBB.
1016 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001017
Evan Cheng10043e22007-01-19 07:51:42 +00001018 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001019 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +00001020 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001021 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001022
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001023 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +00001024 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001025 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +00001026
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001027 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +00001028 // available water after it (but not if it's already there, which happens
1029 // when splitting before a conditional branch that is followed by an
1030 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +00001031 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +00001032 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
1033 CompareMBBNumbers);
1034 MachineBasicBlock* WaterBB = *IP;
1035 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001036 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001037 else
1038 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001039 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001040
Dale Johannesenc17dd572010-07-23 22:50:23 +00001041 // Figure out how large the OrigBB is. As the first half of the original
1042 // block, it cannot contain a tablejump. The size includes
1043 // the new jump we added. (It should be possible to do this without
1044 // recounting everything, but it's very confusing, and this is rarely
1045 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001046 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +00001047
Dale Johannesenc17dd572010-07-23 22:50:23 +00001048 // Figure out how large the NewMBB is. As the second half of the original
1049 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001050 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +00001051
Dale Johannesen01ee5752007-02-25 00:47:03 +00001052 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001053 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +00001054
1055 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +00001056}
1057
Jim Grosbach190e7b62012-03-23 23:07:03 +00001058/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001059/// displacement computation. Update U.KnownAlignment to match its current
1060/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001061unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
1062 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001063 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
1064 unsigned KnownBits = BBI.internalKnownBits();
1065
1066 // The value read from PC is offset from the actual instruction address.
1067 UserOffset += (isThumb ? 4 : 8);
1068
1069 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
1070 // Make sure U.getMaxDisp() returns a constrained range.
1071 U.KnownAlignment = (KnownBits >= 2);
1072
1073 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
1074 // purposes of the displacement computation; compensate for that here.
1075 // For unknown alignments, getMaxDisp() constrains the range instead.
1076 if (isThumb && U.KnownAlignment)
1077 UserOffset &= ~3u;
1078
1079 return UserOffset;
1080}
1081
Jim Grosbach190e7b62012-03-23 23:07:03 +00001082/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001083/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001084/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001085/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001086/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1087/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001088bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001089 unsigned TrialOffset, unsigned MaxDisp,
1090 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001091 if (UserOffset <= TrialOffset) {
1092 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001093 if (TrialOffset - UserOffset <= MaxDisp)
1094 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001095 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001096 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001097 if (UserOffset - TrialOffset <= MaxDisp)
1098 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001099 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001100 }
1101 return false;
1102}
1103
Jim Grosbach190e7b62012-03-23 23:07:03 +00001104/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001105/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001106///
1107/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001108bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001109 MachineBasicBlock* Water, CPUser &U,
1110 unsigned &Growth) {
1111 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1112 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1113 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001114 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001115 if (++NextBlock == MF->end()) {
1116 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1117 NextBlockAlignment = 0;
1118 } else {
1119 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1120 NextBlockAlignment = NextBlock->getAlignment();
1121 }
1122 unsigned Size = U.CPEMI->getOperand(2).getImm();
1123 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001124
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001125 // The CPE may be able to hide in the alignment padding before the next
1126 // block. It may also cause more padding to be required if it is more aligned
1127 // that the next block.
1128 if (CPEEnd > NextBlockOffset) {
1129 Growth = CPEEnd - NextBlockOffset;
1130 // Compute the padding that would go at the end of the CPE to align the next
1131 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001132 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001133
1134 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001135 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001136 // in blocks between CPE and the user.
1137 if (CPEOffset < UserOffset)
1138 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1139 } else
1140 // CPE fits in existing padding.
1141 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001142
Jim Grosbach190e7b62012-03-23 23:07:03 +00001143 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001144}
1145
Jim Grosbach190e7b62012-03-23 23:07:03 +00001146/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001147/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001148bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001149 MachineInstr *CPEMI, unsigned MaxDisp,
1150 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001151 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001152
Dale Johannesene18b13b2007-02-23 05:02:36 +00001153 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001154 DEBUG({
1155 unsigned Block = MI->getParent()->getNumber();
1156 const BasicBlockInfo &BBI = BBInfo[Block];
1157 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1158 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001159 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001160 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001161 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1162 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1163 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001164 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001165 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001166
Jim Grosbach190e7b62012-03-23 23:07:03 +00001167 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001168}
1169
Evan Chenge4510972009-01-28 00:53:34 +00001170#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001171/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1172/// unconditionally branches to its only successor.
1173static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1174 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1175 return false;
1176
1177 MachineBasicBlock *Succ = *MBB->succ_begin();
1178 MachineBasicBlock *Pred = *MBB->pred_begin();
1179 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001180 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1181 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001182 return PredMI->getOperand(0).getMBB() == Succ;
1183 return false;
1184}
Evan Chenge4510972009-01-28 00:53:34 +00001185#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001186
Jim Grosbach190e7b62012-03-23 23:07:03 +00001187void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001188 unsigned BBNum = BB->getNumber();
1189 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001190 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001191 // Include the alignment of the current block.
1192 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1193 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1194 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001195
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001196 // This is where block i begins. Stop if the offset is already correct,
1197 // and we have updated 2 blocks. This is the maximum number of blocks
1198 // changed before calling this function.
1199 if (i > BBNum + 2 &&
1200 BBInfo[i].Offset == Offset &&
1201 BBInfo[i].KnownBits == KnownBits)
1202 break;
1203
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001204 BBInfo[i].Offset = Offset;
1205 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001206 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001207}
1208
Jim Grosbach190e7b62012-03-23 23:07:03 +00001209/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001210/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001211/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001212/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001213
Jim Grosbach190e7b62012-03-23 23:07:03 +00001214bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1215 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001216 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001217 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1218 assert(CPE && "Unexpected!");
1219 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001220 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001221 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001222 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001223 return true;
1224 }
1225 return false;
1226}
1227
Tim Northovera603c402015-05-31 19:22:07 +00001228unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1229 if (CPEMI->getOperand(1).isCPI())
1230 return CPEMI->getOperand(1).getIndex();
1231
1232 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1233}
1234
Dale Johannesene18b13b2007-02-23 05:02:36 +00001235/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1236/// if not, see if an in-range clone of the CPE is in range, and if so,
1237/// change the data structures so the user references the clone. Returns:
1238/// 0 = no existing entry found
1239/// 1 = entry found, and there were no code insertions or deletions
1240/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001241int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001242{
1243 MachineInstr *UserMI = U.MI;
1244 MachineInstr *CPEMI = U.CPEMI;
1245
1246 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001247 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1248 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001249 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001250 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001251 }
1252
Dale Johannesene18b13b2007-02-23 05:02:36 +00001253 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001254 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001255 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1256 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1257 // We already tried this one
1258 if (CPEs[i].CPEMI == CPEMI)
1259 continue;
1260 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001261 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001262 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001263 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001264 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001265 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001266 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001267 // Point the CPUser node to the replacement
1268 U.CPEMI = CPEs[i].CPEMI;
1269 // Change the CPI in the instruction operand to refer to the clone.
1270 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001271 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001272 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001273 break;
1274 }
1275 // Adjust the refcount of the clone...
1276 CPEs[i].RefCount++;
1277 // ...and the original. If we didn't remove the old entry, none of the
1278 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001279 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001280 }
1281 }
1282 return 0;
1283}
1284
Dale Johannesen440995b2007-02-28 18:41:23 +00001285/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1286/// the specific unconditional branch instruction.
1287static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001288 switch (Opc) {
1289 case ARM::tB:
1290 return ((1<<10)-1)*2;
1291 case ARM::t2B:
1292 return ((1<<23)-1)*2;
1293 default:
1294 break;
1295 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001296
David Goodwin27303cd2009-06-30 18:04:13 +00001297 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001298}
1299
Jim Grosbach190e7b62012-03-23 23:07:03 +00001300/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001301/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001302/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001303/// is set to the WaterList entry. For Thumb, prefer water that will not
1304/// introduce padding to water that will. To ensure that this pass
1305/// terminates, the CPE location for a particular CPUser is only allowed to
1306/// move to a lower address, so search backward from the end of the list and
1307/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001308bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001309 water_iterator &WaterIter,
1310 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001311 if (WaterList.empty())
1312 return false;
1313
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001314 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001315 // The nearest water without splitting the UserBB is right after it.
1316 // If the distance is still large (we have a big BB), then we need to split it
1317 // if we don't converge after certain iterations. This helps the following
1318 // situation to converge:
1319 // BB0:
1320 // Big BB
1321 // BB1:
1322 // Constant Pool
1323 // When a CP access is out of range, BB0 may be used as water. However,
1324 // inserting islands between BB0 and BB1 makes other accesses out of range.
1325 MachineBasicBlock *UserBB = U.MI->getParent();
1326 unsigned MinNoSplitDisp =
1327 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1328 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1329 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001330 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001331 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001332 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001333 // Check if water is in range and is either at a lower address than the
1334 // current "high water mark" or a new water block that was created since
1335 // the previous iteration by inserting an unconditional branch. In the
1336 // latter case, we want to allow resetting the high water mark back to
1337 // this new water since we haven't seen it before. Inserting branches
1338 // should be relatively uncommon and when it does happen, we want to be
1339 // sure to take advantage of it for all the CPEs near that block, so that
1340 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001341 // When CloserWater is true, we try to find the lowest address after (or
1342 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001343 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001344 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001345 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001346 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1347 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001348 // This is the least amount of required padding seen so far.
1349 BestGrowth = Growth;
1350 WaterIter = IP;
1351 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1352 << " Growth=" << Growth << '\n');
1353
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001354 if (CloserWater && WaterBB == U.MI->getParent())
1355 return true;
1356 // Keep looking unless it is perfect and we're not looking for the lowest
1357 // possible address.
1358 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001359 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001360 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001361 if (IP == B)
1362 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001363 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001364 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001365}
1366
Jim Grosbach190e7b62012-03-23 23:07:03 +00001367/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001368/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1369/// block is used if in range, and the conditional branch munged so control
1370/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001371/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001372/// block following which the new island can be inserted (the WaterList
1373/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001374void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001375 unsigned UserOffset,
1376 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001377 CPUser &U = CPUsers[CPUserIndex];
1378 MachineInstr *UserMI = U.MI;
1379 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001380 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001381 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001382 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001383
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001384 // If the block does not end in an unconditional branch already, and if the
1385 // end of the block is within range, make new water there. (The addition
1386 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001387 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001388 if (BBHasFallthrough(UserMBB)) {
1389 // Size of branch to insert.
1390 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001391 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001392 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001393
Jim Grosbach190e7b62012-03-23 23:07:03 +00001394 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001395 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1396 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001397 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001398 // Add an unconditional branch from UserMBB to fallthrough block. Record
1399 // it for branch lengthening; this new branch will not get out of range,
1400 // but if the preceding conditional branch is out of range, the targets
1401 // will be exchanged, and the altered branch may be out of range, so the
1402 // machinery has to know about it.
1403 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1404 if (!isThumb)
1405 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1406 else
1407 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1408 .addImm(ARMCC::AL).addReg(0);
1409 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1410 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1411 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001412 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001413 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001414 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001415 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001416 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001417
1418 // What a big block. Find a place within the block to split it. This is a
1419 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1420 // entries are 4 bytes: if instruction I references island CPE, and
1421 // instruction I+1 references CPE', it will not work well to put CPE as far
1422 // forward as possible, since then CPE' cannot immediately follow it (that
1423 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1424 // need to create a new island. So, we make a first guess, then walk through
1425 // the instructions between the one currently being looked at and the
1426 // possible insertion point, and make sure any other instructions that
1427 // reference CPEs will be able to use the same island area; if not, we back
1428 // up the insertion point.
1429
1430 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001431 // point where we can add a 4-byte branch instruction, and then align to
1432 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001433 unsigned LogAlign = MF->getAlignment();
1434 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1435 unsigned KnownBits = UserBBI.internalKnownBits();
1436 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001437 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001438 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1439 BaseInsertOffset));
1440
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001441 // The 4 in the following is for the unconditional branch we'll be inserting
1442 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001443 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001444 BaseInsertOffset -= 4;
1445
1446 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1447 << " la=" << LogAlign
1448 << " kb=" << KnownBits
1449 << " up=" << UPad << '\n');
1450
1451 // This could point off the end of the block if we've already got constant
1452 // pool entries following this block; only the last one is in the water list.
1453 // Back past any possible branches (allow for a conditional and a maximally
1454 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001455 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001456 // Ensure BaseInsertOffset is larger than the offset of the instruction
1457 // following UserMI so that the loop which searches for the split point
1458 // iterates at least once.
1459 BaseInsertOffset =
1460 std::max(UserBBI.postOffset() - UPad - 8,
1461 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001462 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1463 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001464 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001465 CPEMI->getOperand(2).getImm();
1466 MachineBasicBlock::iterator MI = UserMI;
1467 ++MI;
1468 unsigned CPUIndex = CPUserIndex+1;
1469 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001470 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001471 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1472 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001473 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001474 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001475 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1476 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001477 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001478 // Shift intertion point by one unit of alignment so it is within reach.
1479 BaseInsertOffset -= 1u << LogAlign;
1480 EndInsertOffset -= 1u << LogAlign;
1481 }
1482 // This is overly conservative, as we don't account for CPEMIs being
1483 // reused within the block, but it doesn't matter much. Also assume CPEs
1484 // are added in order with alignment padding. We may eventually be able
1485 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001486 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001487 CPUIndex++;
1488 }
1489
1490 // Remember the last IT instruction.
1491 if (MI->getOpcode() == ARM::t2IT)
1492 LastIT = MI;
1493 }
1494
1495 --MI;
1496
1497 // Avoid splitting an IT block.
1498 if (LastIT) {
1499 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001500 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001501 if (CC != ARMCC::AL)
1502 MI = LastIT;
1503 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001504
1505 // We really must not split an IT block.
1506 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001507 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001508
Jim Grosbach190e7b62012-03-23 23:07:03 +00001509 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001510}
1511
Jim Grosbach190e7b62012-03-23 23:07:03 +00001512/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001513/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001514/// place in-range. Return true if we changed any addresses (thus must run
1515/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001516bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1517 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001518 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001519 MachineInstr *UserMI = U.MI;
1520 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001521 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001522 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001523 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001524 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001525
Dale Johannesene18b13b2007-02-23 05:02:36 +00001526 // See if the current entry is within range, or there is a clone of it
1527 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001528 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001529 if (result==1) return false;
1530 else if (result==2) return true;
1531
1532 // No existing clone of this CPE is within range.
1533 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001534 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001535
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001536 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001537 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001538 MachineBasicBlock *NewMBB;
1539 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001540 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001541 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001542 MachineBasicBlock *WaterBB = *IP;
1543
1544 // If the original WaterList entry was "new water" on this iteration,
1545 // propagate that to the new island. This is just keeping NewWaterList
1546 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001547 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001548 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001549
Bob Wilson2f9be502009-10-15 20:49:47 +00001550 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001551 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001552 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001553 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001554 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001555 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001556
Jim Grosbach190e7b62012-03-23 23:07:03 +00001557 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001558 // called while handling branches so that the water will be seen on the
1559 // next iteration for constant pools, but in this context, we don't want
1560 // it. Check for this so it will be removed from the WaterList.
1561 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001562 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001563 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1564 if (IP != WaterList.end())
1565 NewWaterList.erase(WaterBB);
1566
1567 // We are adding new water. Update NewWaterList.
1568 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001569 }
1570
Bob Wilson2f9be502009-10-15 20:49:47 +00001571 // Remove the original WaterList entry; we want subsequent insertions in
1572 // this vicinity to go after the one we're about to insert. This
1573 // considerably reduces the number of times we have to move the same CPE
1574 // more than once and is also important to ensure the algorithm terminates.
1575 if (IP != WaterList.end())
1576 WaterList.erase(IP);
1577
Dale Johannesene18b13b2007-02-23 05:02:36 +00001578 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001579 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001580
1581 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001582 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001583
Dale Johannesene18b13b2007-02-23 05:02:36 +00001584 // Now that we have an island to add the CPE to, clone the original CPE and
1585 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001586 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001587 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1588 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001589 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001590 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001591
Tim Northovera603c402015-05-31 19:22:07 +00001592 // Decrement the old entry, and remove it if refcount becomes 0.
1593 decrementCPEReferenceCount(CPI, CPEMI);
1594
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001595 // Mark the basic block as aligned as required by the const-pool entry.
1596 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001597
Evan Cheng10043e22007-01-19 07:51:42 +00001598 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001599 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001600 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001601
Evan Cheng10043e22007-01-19 07:51:42 +00001602 // Finally, change the CPI in the instruction operand to be ID.
1603 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001604 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001605 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001606 break;
1607 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001608
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001609 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001610 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001611
Evan Cheng10043e22007-01-19 07:51:42 +00001612 return true;
1613}
1614
Jim Grosbach190e7b62012-03-23 23:07:03 +00001615/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001616/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001617void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001618 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001619 unsigned Size = CPEMI->getOperand(2).getImm();
1620 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001621 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001622 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001623 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001624 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001625
Evan Chengab28b9a2013-02-21 18:37:54 +00001626 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001627 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001628 } else
1629 // Entries are sorted by descending alignment, so realign from the front.
1630 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1631
Jim Grosbach190e7b62012-03-23 23:07:03 +00001632 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001633 // An island has only one predecessor BB and one successor BB. Check if
1634 // this BB's predecessor jumps directly to this BB's successor. This
1635 // shouldn't happen currently.
1636 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1637 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001638}
1639
Jim Grosbach190e7b62012-03-23 23:07:03 +00001640/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001641/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001642bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001643 unsigned MadeChange = false;
1644 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1645 std::vector<CPEntry> &CPEs = CPEntries[i];
1646 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1647 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001648 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001649 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001650 MadeChange = true;
1651 }
1652 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001653 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001654 return MadeChange;
1655}
1656
Jim Grosbach190e7b62012-03-23 23:07:03 +00001657/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001658/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001659bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001660 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001661 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001662 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001663 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001664
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001665 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001666 << " from BB#" << MI->getParent()->getNumber()
1667 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001668 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001669 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001670
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001671 if (BrOffset <= DestOffset) {
1672 // Branch before the Dest.
1673 if (DestOffset-BrOffset <= MaxDisp)
1674 return true;
1675 } else {
1676 if (BrOffset-DestOffset <= MaxDisp)
1677 return true;
1678 }
1679 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001680}
1681
Jim Grosbach190e7b62012-03-23 23:07:03 +00001682/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001683/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001684bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001685 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001686 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001687
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001688 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001689 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001690 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001691
Evan Cheng7fa69642007-01-30 01:18:38 +00001692 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001693 return fixupUnconditionalBr(Br);
1694 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001695}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001696
Jim Grosbach190e7b62012-03-23 23:07:03 +00001697/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001698/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001699/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001700/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001701bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001702ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001703 MachineInstr *MI = Br.MI;
1704 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001705 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001706 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001707
1708 // Use BL to implement far jump.
1709 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001710 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001711 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001712 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001713 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001714 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001715
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001716 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001717
Evan Cheng7fa69642007-01-30 01:18:38 +00001718 return true;
1719}
1720
Jim Grosbach190e7b62012-03-23 23:07:03 +00001721/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001722/// far away to fit in its displacement field. It is converted to an inverse
1723/// conditional branch + an unconditional branch to the destination.
1724bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001725ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001726 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001727 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001728
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001729 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001730 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001731 // blt L1
1732 // =>
1733 // bge L2
1734 // b L1
1735 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001736 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001737 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001738 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001739
1740 // If the branch is at the end of its MBB and that has a fall-through block,
1741 // direct the updated conditional branch to the fall-through block. Otherwise,
1742 // split the MBB before the next instruction.
1743 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001744 MachineInstr *BMI = &MBB->back();
1745 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001746
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001747 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001748 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001749 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001750 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001751 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001752 // condition and swap destinations:
1753 // beq L1
1754 // b L2
1755 // =>
1756 // bne L2
1757 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001758 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001759 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001760 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001761 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001762 BMI->getOperand(0).setMBB(DestBB);
1763 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001764 MI->getOperand(1).setImm(CC);
1765 return true;
1766 }
1767 }
1768 }
1769
1770 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001771 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001772 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001773 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001774 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001775 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001776 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001777 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001778 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001779 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001780
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001781 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001782 << " also invert condition and change dest. to BB#"
1783 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001784
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001785 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001786 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001787 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001788 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001789 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001790 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001791 if (isThumb)
1792 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1793 .addImm(ARMCC::AL).addReg(0);
1794 else
1795 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001796 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001797 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001798 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001799
1800 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001801 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001802 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001803 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001804 return true;
1805}
Evan Cheng7fa69642007-01-30 01:18:38 +00001806
Jim Grosbach190e7b62012-03-23 23:07:03 +00001807/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001808/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1809/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001810bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001811 bool MadeChange = false;
1812 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1813 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001814 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001815 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001816 MI->getOperand(2).getReg() == ARM::PC &&
1817 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001818 // Create the new insn and copy the predicate from the old.
1819 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1820 .addOperand(MI->getOperand(0))
1821 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001822 MI->eraseFromParent();
1823 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001824 }
1825 }
1826 return MadeChange;
1827}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001828
Jim Grosbach190e7b62012-03-23 23:07:03 +00001829// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001830// below may shrink MI.
1831bool
1832ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1833 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001834 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001835 case ARM::t2LEApcrel:
1836 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001837 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001838 case ARM::t2B:
1839 case ARM::t2Bcc:
1840 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001841 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001842 case ARM::t2BR_JT:
1843 return true;
1844 }
1845 return false;
1846}
1847
Jim Grosbach190e7b62012-03-23 23:07:03 +00001848bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001849 bool MadeChange = false;
1850
1851 // Shrink ADR and LDR from constantpool.
1852 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1853 CPUser &U = CPUsers[i];
1854 unsigned Opcode = U.MI->getOpcode();
1855 unsigned NewOpc = 0;
1856 unsigned Scale = 1;
1857 unsigned Bits = 0;
1858 switch (Opcode) {
1859 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001860 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001861 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1862 NewOpc = ARM::tLEApcrel;
1863 Bits = 8;
1864 Scale = 4;
1865 }
1866 break;
1867 case ARM::t2LDRpci:
1868 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1869 NewOpc = ARM::tLDRpci;
1870 Bits = 8;
1871 Scale = 4;
1872 }
1873 break;
1874 }
1875
1876 if (!NewOpc)
1877 continue;
1878
Jim Grosbach190e7b62012-03-23 23:07:03 +00001879 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001880 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001881
1882 // Be conservative with inline asm.
1883 if (!U.KnownAlignment)
1884 MaxOffs -= 2;
1885
Evan Chengdb73d682009-08-14 00:32:16 +00001886 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001887 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001888 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001889 U.MI->setDesc(TII->get(NewOpc));
1890 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001891 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001892 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001893 ++NumT2CPShrunk;
1894 MadeChange = true;
1895 }
1896 }
1897
Evan Chengdb73d682009-08-14 00:32:16 +00001898 return MadeChange;
1899}
1900
Jim Grosbach190e7b62012-03-23 23:07:03 +00001901bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001902 bool MadeChange = false;
1903
Peter Collingbourne167668f2015-04-23 20:31:35 +00001904 // The order in which branches appear in ImmBranches is approximately their
1905 // order within the function body. By visiting later branches first, we reduce
1906 // the distance between earlier forward branches and their targets, making it
1907 // more likely that the cbn?z optimization, which can only apply to forward
1908 // branches, will succeed.
1909 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1910 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001911 unsigned Opcode = Br.MI->getOpcode();
1912 unsigned NewOpc = 0;
1913 unsigned Scale = 1;
1914 unsigned Bits = 0;
1915 switch (Opcode) {
1916 default: break;
1917 case ARM::t2B:
1918 NewOpc = ARM::tB;
1919 Bits = 11;
1920 Scale = 2;
1921 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001922 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001923 NewOpc = ARM::tBcc;
1924 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001925 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001926 break;
1927 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001928 }
1929 if (NewOpc) {
1930 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1931 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001932 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001933 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001934 Br.MI->setDesc(TII->get(NewOpc));
1935 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001936 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001937 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001938 ++NumT2BrShrunk;
1939 MadeChange = true;
1940 }
1941 }
1942
1943 Opcode = Br.MI->getOpcode();
1944 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001945 continue;
1946
Evan Cheng6bb95252012-01-14 01:53:46 +00001947 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1948 // so this transformation is not safe.
1949 if (!Br.MI->killsRegister(ARM::CPSR))
1950 continue;
1951
Evan Cheng6f29ad92009-10-31 23:46:45 +00001952 NewOpc = 0;
1953 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001954 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001955 if (Pred == ARMCC::EQ)
1956 NewOpc = ARM::tCBZ;
1957 else if (Pred == ARMCC::NE)
1958 NewOpc = ARM::tCBNZ;
1959 if (!NewOpc)
1960 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001961 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001962 // Check if the distance is within 126. Subtract starting offset by 2
1963 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001964 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001965 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001966 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001967 MachineBasicBlock::iterator CmpMI = Br.MI;
1968 if (CmpMI != Br.MI->getParent()->begin()) {
1969 --CmpMI;
1970 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1971 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001972 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001973 if (Pred == ARMCC::AL &&
1974 CmpMI->getOperand(1).getImm() == 0 &&
1975 isARMLowRegister(Reg)) {
1976 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001977 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001978 MachineInstr *NewBR =
1979 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1980 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1981 CmpMI->eraseFromParent();
1982 Br.MI->eraseFromParent();
1983 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001984 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001985 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001986 ++NumCBZ;
1987 MadeChange = true;
1988 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001989 }
1990 }
Evan Chenge41903b2009-08-14 18:31:44 +00001991 }
1992 }
1993
1994 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001995}
1996
Tim Northovera603c402015-05-31 19:22:07 +00001997static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1998 unsigned BaseReg) {
1999 if (I.getOpcode() != ARM::t2ADDrs)
2000 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002001
Tim Northovera603c402015-05-31 19:22:07 +00002002 if (I.getOperand(0).getReg() != EntryReg)
2003 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002004
Tim Northovera603c402015-05-31 19:22:07 +00002005 if (I.getOperand(1).getReg() != BaseReg)
2006 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002007
Tim Northovera603c402015-05-31 19:22:07 +00002008 // FIXME: what about CC and IdxReg?
2009 return true;
2010}
Tim Northover688f7bb2015-05-13 20:28:32 +00002011
Tim Northovera603c402015-05-31 19:22:07 +00002012/// \brief While trying to form a TBB/TBH instruction, we may (if the table
2013/// doesn't immediately follow the BR_JT) need access to the start of the
2014/// jump-table. We know one instruction that produces such a register; this
2015/// function works out whether that definition can be preserved to the BR_JT,
2016/// possibly by removing an intervening addition (which is usually needed to
2017/// calculate the actual entry to jump to).
2018bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
2019 MachineInstr *LEAMI,
2020 unsigned &DeadSize,
2021 bool &CanDeleteLEA,
2022 bool &BaseRegKill) {
2023 if (JumpMI->getParent() != LEAMI->getParent())
2024 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00002025
Tim Northovera603c402015-05-31 19:22:07 +00002026 // Now we hope that we have at least these instructions in the basic block:
2027 // BaseReg = t2LEA ...
2028 // [...]
2029 // EntryReg = t2ADDrs BaseReg, ...
2030 // [...]
2031 // t2BR_JT EntryReg
2032 //
2033 // We have to be very conservative about what we recognise here though. The
2034 // main perturbing factors to watch out for are:
2035 // + Spills at any point in the chain: not direct problems but we would
2036 // expect a blocking Def of the spilled register so in practice what we
2037 // can do is limited.
2038 // + EntryReg == BaseReg: this is the one situation we should allow a Def
2039 // of BaseReg, but only if the t2ADDrs can be removed.
2040 // + Some instruction other than t2ADDrs computing the entry. Not seen in
2041 // the wild, but we should be careful.
2042 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2043 unsigned BaseReg = LEAMI->getOperand(0).getReg();
2044
2045 CanDeleteLEA = true;
2046 BaseRegKill = false;
2047 MachineInstr *RemovableAdd = nullptr;
2048 MachineBasicBlock::iterator I(LEAMI);
2049 for (++I; &*I != JumpMI; ++I) {
2050 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2051 RemovableAdd = &*I;
2052 break;
2053 }
2054
2055 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2056 const MachineOperand &MO = I->getOperand(K);
2057 if (!MO.isReg() || !MO.getReg())
2058 continue;
2059 if (MO.isDef() && MO.getReg() == BaseReg)
2060 return false;
2061 if (MO.isUse() && MO.getReg() == BaseReg) {
2062 BaseRegKill = BaseRegKill || MO.isKill();
2063 CanDeleteLEA = false;
2064 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002065 }
2066 }
2067
Tim Northovera603c402015-05-31 19:22:07 +00002068 if (!RemovableAdd)
2069 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00002070
Tim Northovera603c402015-05-31 19:22:07 +00002071 // Check the add really is removable, and that nothing else in the block
2072 // clobbers BaseReg.
2073 for (++I; &*I != JumpMI; ++I) {
2074 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2075 const MachineOperand &MO = I->getOperand(K);
2076 if (!MO.isReg() || !MO.getReg())
2077 continue;
2078 if (MO.isDef() && MO.getReg() == BaseReg)
2079 return false;
2080 if (MO.isUse() && MO.getReg() == EntryReg)
2081 RemovableAdd = nullptr;
2082 }
2083 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002084
Tim Northovera603c402015-05-31 19:22:07 +00002085 if (RemovableAdd) {
2086 RemovableAdd->eraseFromParent();
2087 DeadSize += 4;
2088 } else if (BaseReg == EntryReg) {
2089 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2090 // preserve it.
2091 return false;
2092 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002093
Tim Northovera603c402015-05-31 19:22:07 +00002094 // We reached the end of the block without seeing another definition of
2095 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2096 // used in the TBB/TBH if necessary.
2097 return true;
2098}
Tim Northover688f7bb2015-05-13 20:28:32 +00002099
Tim Northovera603c402015-05-31 19:22:07 +00002100/// \brief Returns whether CPEMI is the first instruction in the block
2101/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2102/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002103/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002104static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002105 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002106 MachineFunction *MF = MBB->getParent();
2107 ++MBB;
2108
2109 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2110 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002111}
2112
Jim Grosbach190e7b62012-03-23 23:07:03 +00002113/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002114/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002115bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002116 bool MadeChange = false;
2117
2118 // FIXME: After the tables are shrunk, can we get rid some of the
2119 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002120 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002121 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002122
Evan Chengc6d70ae2009-07-29 02:18:14 +00002123 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2124 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2125 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002126 const MCInstrDesc &MCID = MI->getDesc();
2127 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002128 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002129 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2130 unsigned JTI = JTOP.getIndex();
2131 assert(JTI < JT.size());
2132
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002133 bool ByteOk = true;
2134 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002135 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002136 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002137 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2138 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002139 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002140 // Negative offset is not ok. FIXME: We should change BB layout to make
2141 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002142 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002143 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002144 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002145 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002146 HalfWordOk = false;
2147 if (!ByteOk && !HalfWordOk)
2148 break;
2149 }
2150
Tim Northovera603c402015-05-31 19:22:07 +00002151 if (!ByteOk && !HalfWordOk)
2152 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002153
Tim Northovera603c402015-05-31 19:22:07 +00002154 MachineBasicBlock *MBB = MI->getParent();
2155 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2156 continue;
2157 unsigned IdxReg = MI->getOperand(1).getReg();
2158 bool IdxRegKill = MI->getOperand(1).isKill();
2159
2160 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2161 unsigned DeadSize = 0;
2162 bool CanDeleteLEA = false;
2163 bool BaseRegKill = false;
2164 bool PreservedBaseReg =
2165 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2166
2167 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2168 continue;
2169
2170 DEBUG(dbgs() << "Shrink JT: " << *MI);
2171 MachineInstr *CPEMI = User.CPEMI;
2172 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2173 MachineBasicBlock::iterator MI_JT = MI;
2174 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002175 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002176 .addReg(User.MI->getOperand(0).getReg(),
2177 getKillRegState(BaseRegKill))
2178 .addReg(IdxReg, getKillRegState(IdxRegKill))
2179 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2180 .addImm(CPEMI->getOperand(0).getImm());
2181 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002182
Tim Northovera603c402015-05-31 19:22:07 +00002183 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2184 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002185
Tim Northovera603c402015-05-31 19:22:07 +00002186 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2187 NewJTMI->getOperand(0).setReg(ARM::PC);
2188 NewJTMI->getOperand(0).setIsKill(false);
2189
2190 if (CanDeleteLEA) {
2191 User.MI->eraseFromParent();
2192 DeadSize += 4;
2193
2194 // The LEA was eliminated, the TBB instruction becomes the only new user
2195 // of the jump table.
2196 User.MI = NewJTMI;
2197 User.MaxDisp = 4;
2198 User.NegOk = false;
2199 User.IsSoImm = false;
2200 User.KnownAlignment = false;
2201 } else {
2202 // The LEA couldn't be eliminated, so we must add another CPUser to
2203 // record the TBB or TBH use.
2204 int CPEntryIdx = JumpTableEntryIndices[JTI];
2205 auto &CPEs = CPEntries[CPEntryIdx];
2206 auto Entry = std::find_if(CPEs.begin(), CPEs.end(), [&](CPEntry &E) {
2207 return E.CPEMI == User.CPEMI;
2208 });
2209 ++Entry->RefCount;
2210 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2211 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002212 }
Tim Northovera603c402015-05-31 19:22:07 +00002213
2214 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
2215 unsigned OrigSize = TII->GetInstSizeInBytes(MI);
2216 MI->eraseFromParent();
2217
2218 int Delta = OrigSize - NewSize + DeadSize;
2219 BBInfo[MBB->getNumber()].Size -= Delta;
2220 adjustBBOffsetsAfter(MBB);
2221
2222 ++NumTBs;
2223 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002224 }
2225
2226 return MadeChange;
2227}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002228
Jim Grosbach190e7b62012-03-23 23:07:03 +00002229/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002230/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002231bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002232 bool MadeChange = false;
2233
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002234 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002235 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002236
Jim Grosbach5d577142009-11-12 17:25:07 +00002237 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2238 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2239 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002240 const MCInstrDesc &MCID = MI->getDesc();
2241 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002242 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002243 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2244 unsigned JTI = JTOP.getIndex();
2245 assert(JTI < JT.size());
2246
2247 // We prefer if target blocks for the jump table come after the jump
2248 // instruction so we can use TB[BH]. Loop through the target blocks
2249 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002250 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002251 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2252 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2253 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002254 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002255
Jim Grosbach9785e592009-11-16 18:58:52 +00002256 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002257 // The destination precedes the switch. Try to move the block forward
2258 // so we have a positive offset.
2259 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002260 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002261 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002262 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002263 MadeChange = true;
2264 }
2265 }
2266 }
2267
2268 return MadeChange;
2269}
2270
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002271MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002272adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002273 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002274 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002275 // table that branches back to the actual target. This is a very simple
2276 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002277 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002278 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002279 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002280 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002281 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002282
Jim Grosbach47d5e332009-11-16 17:10:56 +00002283 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002284 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002285
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002286 // If the block ends in an unconditional branch, move it. The prior block
2287 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002288 // 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 +00002289 if (!B && Cond.empty() && BB != &MF->front() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002290 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002291 BB->moveAfter(JTBB);
2292 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002293 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002294 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002295 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002296 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002297 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002298 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002299
2300 // Create a new MBB for the code after the jump BB.
2301 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002302 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002303 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002304 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002305
2306 // Add an unconditional branch from NewBB to BB.
2307 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2308 // correspond directly to anything in the source.
2309 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002310 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2311 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002312
Jim Grosbach43d21082009-11-14 20:10:18 +00002313 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002314 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002315
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002316 // Update the CFG.
2317 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002318 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002319
Jim Grosbach5d577142009-11-12 17:25:07 +00002320 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002321 return NewBB;
2322}