blob: c50c5f23ccaba2445aa51b85d540533f1a59ff7f [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"
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +000017#include "ARMBasicBlockInfo.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "Thumb2InstrInfo.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000025#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000027#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Support/CommandLine.h"
Evan Cheng10043e22007-01-19 07:51:42 +000031#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000033#include "llvm/Support/Format.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetMachine.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000036#include <algorithm>
Evan Cheng10043e22007-01-19 07:51:42 +000037using namespace llvm;
38
Chandler Carruth84e68b22014-04-22 02:41:26 +000039#define DEBUG_TYPE "arm-cp-islands"
40
Evan Chengdb73d682009-08-14 00:32:16 +000041STATISTIC(NumCPEs, "Number of constpool entries");
42STATISTIC(NumSplit, "Number of uncond branches inserted");
43STATISTIC(NumCBrFixed, "Number of cond branches fixed");
44STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
45STATISTIC(NumTBs, "Number of table branches generated");
46STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000047STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000048STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000049STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000050STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000051
52
53static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000054AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000055 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000056
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000057static cl::opt<unsigned>
58CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
59 cl::desc("The max number of iteration for converge"));
60
James Molloy70a3d6d2016-11-01 13:37:41 +000061static cl::opt<bool> SynthesizeThumb1TBB(
62 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
63 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
64 "equivalent to the TBB/TBH instructions"));
65
Evan Cheng10043e22007-01-19 07:51:42 +000066namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000067 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000068 /// requires constant pool entries to be scattered among the instructions
69 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000070 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000071 /// special instructions.
72 ///
73 /// The terminology used in this pass includes:
74 /// Islands - Clumps of constants placed in the function.
75 /// Water - Potential places where an island could be formed.
76 /// CPE - A constant pool entry that has been placed somewhere, which
77 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000078 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000079
80 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +000081
Evan Cheng10043e22007-01-19 07:51:42 +000082 /// WaterList - A sorted list of basic blocks where islands could be placed
83 /// (i.e. blocks that don't fall through to the following block, due
84 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +000085 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +000086
Bob Wilson2f9be502009-10-15 20:49:47 +000087 /// NewWaterList - The subset of WaterList that was created since the
88 /// previous iteration by inserting unconditional branches.
89 SmallSet<MachineBasicBlock*, 4> NewWaterList;
90
Bob Wilsonc7a3cf42009-10-12 18:52:13 +000091 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
92
Evan Cheng10043e22007-01-19 07:51:42 +000093 /// CPUser - One user of a constant pool, keeping the machine instruction
94 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +000095 /// allowed from the instruction to the CP. The HighWaterMark records the
96 /// highest basic block where a new CPEntry can be placed. To ensure this
97 /// pass terminates, the CP entries are initially placed at the end of the
98 /// function and then move monotonically to lower addresses. The
99 /// exception to this rule is when the current CP entry for a particular
100 /// CPUser is out of range, but there is another CP entry for the same
101 /// constant value in range. We want to use the existing in-range CP
102 /// entry, but if it later moves out of range, the search for new water
103 /// should resume where it left off. The HighWaterMark is used to record
104 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000105 struct CPUser {
106 MachineInstr *MI;
107 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000108 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000109 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000110 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000111 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000112 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000113 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
114 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000115 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
116 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000117 HighWaterMark = CPEMI->getParent();
118 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000119 /// getMaxDisp - Returns the maximum displacement supported by MI.
120 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000121 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000122 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000123 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000124 }
Evan Cheng10043e22007-01-19 07:51:42 +0000125 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000126
Evan Cheng10043e22007-01-19 07:51:42 +0000127 /// CPUsers - Keep track of all of the machine instructions that use various
128 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000129 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000130
Evan Cheng8b7700f2007-02-09 20:54:44 +0000131 /// CPEntry - One per constant pool entry, keeping the machine instruction
132 /// pointer, the constpool index, and the number of CPUser's which
133 /// reference this entry.
134 struct CPEntry {
135 MachineInstr *CPEMI;
136 unsigned CPI;
137 unsigned RefCount;
138 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
139 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
140 };
141
142 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000143 /// instructions. For each original constpool index (i.e. those that existed
144 /// upon entry to this pass), it keeps a vector of entries. Original
145 /// elements are cloned as we go along; the clones are put in the vector of
146 /// the original element, but have distinct CPIs.
147 ///
148 /// The first half of CPEntries contains generic constants, the second half
149 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
150 /// which vector it will be in here.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000151 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000152
Tim Northovera603c402015-05-31 19:22:07 +0000153 /// Maps a JT index to the offset in CPEntries containing copies of that
154 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
155 DenseMap<int, int> JumpTableEntryIndices;
156
157 /// Maps a JT index to the LEA that actually uses the index to calculate its
158 /// base address.
159 DenseMap<int, int> JumpTableUserIndices;
160
Evan Cheng22c7cf52007-01-25 03:12:46 +0000161 /// ImmBranch - One per immediate branch, keeping the machine instruction
162 /// pointer, conditional or unconditional, the max displacement,
163 /// and (if isCond is true) the corresponding unconditional branch
164 /// opcode.
165 struct ImmBranch {
166 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000167 unsigned MaxDisp : 31;
168 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000169 unsigned UncondBr;
170 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000171 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000172 };
173
Evan Chengc95f95b2007-05-16 05:14:06 +0000174 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000175 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000176 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000177
Evan Cheng7fa69642007-01-30 01:18:38 +0000178 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
179 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000180 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000181
Evan Chengc6d70ae2009-07-29 02:18:14 +0000182 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
183 SmallVector<MachineInstr*, 4> T2JumpTables;
184
Evan Cheng7fa69642007-01-30 01:18:38 +0000185 /// HasFarJump - True if any far jump instruction has been emitted during
186 /// the branch fix up pass.
187 bool HasFarJump;
188
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000189 MachineFunction *MF;
190 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000191 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000192 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000193 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000194 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000195 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000196 bool isThumb2;
James Molloy70a3d6d2016-11-01 13:37:41 +0000197 bool isPositionIndependentOrROPI;
Evan Cheng10043e22007-01-19 07:51:42 +0000198 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000199 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000200 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000201
Craig Topper6bc27bf2014-03-10 02:09:33 +0000202 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000203
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000204 MachineFunctionProperties getRequiredProperties() const override {
205 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000206 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000207 }
208
Mehdi Amini117296c2016-10-01 02:56:57 +0000209 StringRef getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000210 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000211 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000212
Evan Cheng10043e22007-01-19 07:51:42 +0000213 private:
Tim Northovera603c402015-05-31 19:22:07 +0000214 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
215 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000216 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000217 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000218 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000219 void scanFunctionJumpTables();
220 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
221 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
222 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
223 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
224 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000225 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000226 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
227 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000228 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000229 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000230 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000231 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000232 void removeDeadCPEMI(MachineInstr *CPEMI);
233 bool removeUnusedCPEntries();
234 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
235 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
236 bool DoDump = false);
237 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000238 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000239 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
240 bool fixupImmediateBr(ImmBranch &Br);
241 bool fixupConditionalBr(ImmBranch &Br);
242 bool fixupUnconditionalBr(ImmBranch &Br);
243 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000244 bool optimizeThumb2Instructions();
245 bool optimizeThumb2Branches();
246 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000247 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
248 unsigned &DeadSize, bool &CanDeleteLEA,
249 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000250 bool optimizeThumb2JumpTables();
251 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000252 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000253
Jim Grosbach190e7b62012-03-23 23:07:03 +0000254 unsigned getOffsetOf(MachineInstr *MI) const;
255 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000256 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000257 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000258
Jim Grosbach190e7b62012-03-23 23:07:03 +0000259 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000260 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000261 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000262 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000263 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000264 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000265 }
Evan Cheng10043e22007-01-19 07:51:42 +0000266 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000267 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000268}
Evan Cheng10043e22007-01-19 07:51:42 +0000269
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000270/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000271void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000272#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000273 assert(std::is_sorted(MF->begin(), MF->end(),
274 [this](const MachineBasicBlock &LHS,
275 const MachineBasicBlock &RHS) {
276 return BBInfo[LHS.getNumber()].postOffset() <
277 BBInfo[RHS.getNumber()].postOffset();
278 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000279 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000280 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
281 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000282 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000283 // Verify offset using the real max displacement without the safety
284 // adjustment.
285 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000286 /* DoDump = */ true)) {
287 DEBUG(dbgs() << "OK\n");
288 continue;
289 }
290 DEBUG(dbgs() << "Out of range.\n");
291 dumpBBs();
292 DEBUG(MF->dump());
293 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000294 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000295#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000296}
297
298/// print block size and offset information - debugging
299void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000300 DEBUG({
301 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
302 const BasicBlockInfo &BBI = BBInfo[J];
303 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
304 << " kb=" << unsigned(BBI.KnownBits)
305 << " ua=" << unsigned(BBI.Unalign)
306 << " pa=" << unsigned(BBI.PostAlign)
307 << format(" size=%#x\n", BBInfo[J].Size);
308 }
309 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000310}
311
Evan Cheng22c7cf52007-01-25 03:12:46 +0000312/// createARMConstantIslandPass - returns an instance of the constpool
313/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000314FunctionPass *llvm::createARMConstantIslandPass() {
315 return new ARMConstantIslands();
316}
317
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000318bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
319 MF = &mf;
320 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000321
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000322 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000323 << MCP->getConstants().size() << " CP entries, aligned to "
324 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000325
Eric Christopher1b21f002015-01-29 00:19:33 +0000326 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
327 TII = STI->getInstrInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +0000328 isPositionIndependentOrROPI =
329 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000330 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000331
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000332 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000333 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000334 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000335
336 HasFarJump = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000337 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
Evan Cheng7fa69642007-01-30 01:18:38 +0000338
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000339 // This pass invalidates liveness information when it splits basic blocks.
340 MF->getRegInfo().invalidateLiveness();
341
Evan Cheng10043e22007-01-19 07:51:42 +0000342 // Renumber all of the machine basic blocks in the function, guaranteeing that
343 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000344 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000345
Jim Grosbach5d577142009-11-12 17:25:07 +0000346 // Try to reorder and otherwise adjust the block layout to make good use
347 // of the TB[BH] instructions.
348 bool MadeChange = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000349 if (GenerateTBB && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000350 scanFunctionJumpTables();
351 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000352 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000353 T2JumpTables.clear();
354 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000355 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000356 }
357
Evan Cheng10043e22007-01-19 07:51:42 +0000358 // Perform the initial placement of the constant pool entries. To start with,
359 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000360 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000361 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000362 doInitialConstPlacement(CPEMIs);
363
364 if (MF->getJumpTableInfo())
365 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000366
Evan Cheng10043e22007-01-19 07:51:42 +0000367 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000368 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000369
Evan Cheng10043e22007-01-19 07:51:42 +0000370 // Do the initial scan of the function, building up information about the
371 // sizes of each block, the location of all the water, and finding all of the
372 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000373 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000374 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000375 DEBUG(dumpBBs());
376
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000377 // Functions with jump tables need an alignment of 4 because they use the ADR
378 // instruction, which aligns the PC to 4 bytes before adding an offset.
379 if (!T2JumpTables.empty())
380 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000381
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000382 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000383 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000384
Evan Cheng7fa69642007-01-30 01:18:38 +0000385 // Iteratively place constant pool entries and fix up branches until there
386 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000387 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000388 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000389 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000390 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000391 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000392 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000393 // If it doesn't end in 10, the input may have huge BB or many CPEs.
394 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000395 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
396 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000397 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000398 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000399
Bob Wilson2f9be502009-10-15 20:49:47 +0000400 // Clear NewWaterList now. If we split a block for branches, it should
401 // appear as "new water" for the next iteration of constant pool placement.
402 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000403
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000404 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000405 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000406 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000407 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000408 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000409 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000410 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000411
412 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000413 break;
414 MadeChange = true;
415 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000416
Bradley Smitha1189102016-01-15 10:26:17 +0000417 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000418 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000419 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000420
Bradley Smitha1189102016-01-15 10:26:17 +0000421 // Shrink 32-bit branch instructions.
422 if (isThumb && STI->hasV8MBaselineOps())
423 MadeChange |= optimizeThumb2Branches();
424
425 // Optimize jump tables using TBB / TBH.
James Molloy70a3d6d2016-11-01 13:37:41 +0000426 if (GenerateTBB)
Bradley Smitha1189102016-01-15 10:26:17 +0000427 MadeChange |= optimizeThumb2JumpTables();
428
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000429 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000430 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000431
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000432 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
433 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000434 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000435 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000436
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000437 // Save the mapping between original and cloned constpool entries.
438 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
439 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
440 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000441 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
442 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000443 }
444 }
445
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000446 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000447
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000448 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000449 WaterList.clear();
450 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000451 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000452 JumpTableEntryIndices.clear();
453 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000454 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000455 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000456 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000457
458 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000459}
460
Tim Northovera603c402015-05-31 19:22:07 +0000461/// \brief Perform the initial placement of the regular constant pool entries.
462/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000463void
Tim Northovera603c402015-05-31 19:22:07 +0000464ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000465 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000466 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
467 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000468
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000469 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000470 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000471
472 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000473 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000474
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000475 // The function needs to be as aligned as the basic blocks. The linker may
476 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000477 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000478
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000479 // Order the entries in BB by descending alignment. That ensures correct
480 // alignment of all entries as long as BB is sufficiently aligned. Keep
481 // track of the insertion point for each alignment. We are going to bucket
482 // sort the entries as they are created.
483 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000484
Evan Cheng10043e22007-01-19 07:51:42 +0000485 // Add all of the constants from the constant pool to the end block, use an
486 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000487 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000488
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000489 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000490 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000491 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000492 assert(Size >= 4 && "Too small constant pool entry");
493 unsigned Align = CPs[i].getAlignment();
494 assert(isPowerOf2_32(Align) && "Invalid alignment");
495 // Verify that all constant pool entries are a multiple of their alignment.
496 // If not, we would have to pad them out so that instructions stay aligned.
497 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
498
499 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
500 unsigned LogAlign = Log2_32(Align);
501 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000502 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000503 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000504 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000505 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000506
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000507 // Ensure that future entries with higher alignment get inserted before
508 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000509 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000510 if (InsPoint[a] == InsAt)
511 InsPoint[a] = CPEMI;
512
Evan Cheng8b7700f2007-02-09 20:54:44 +0000513 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000514 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000515 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000516 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
517 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000518 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000519 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000520}
521
Tim Northovera603c402015-05-31 19:22:07 +0000522/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
523/// instructions can be made more efficient if the jump table immediately
524/// follows the instruction, it's best to place them immediately next to their
525/// jumps to begin with. In almost all cases they'll never be moved from that
526/// position.
527void ARMConstantIslands::doInitialJumpTablePlacement(
528 std::vector<MachineInstr *> &CPEMIs) {
529 unsigned i = CPEntries.size();
530 auto MJTI = MF->getJumpTableInfo();
531 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
532
533 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
534 for (MachineBasicBlock &MBB : *MF) {
535 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000536 if (MI == MBB.end())
537 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000538
539 unsigned JTOpcode;
540 switch (MI->getOpcode()) {
541 default:
542 continue;
543 case ARM::BR_JTadd:
544 case ARM::BR_JTr:
545 case ARM::tBR_JTr:
546 case ARM::BR_JTm:
547 JTOpcode = ARM::JUMPTABLE_ADDRS;
548 break;
549 case ARM::t2BR_JT:
550 JTOpcode = ARM::JUMPTABLE_INSTS;
551 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000552 case ARM::tTBB_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000553 case ARM::t2TBB_JT:
554 JTOpcode = ARM::JUMPTABLE_TBB;
555 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000556 case ARM::tTBH_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000557 case ARM::t2TBH_JT:
558 JTOpcode = ARM::JUMPTABLE_TBH;
559 break;
560 }
561
562 unsigned NumOps = MI->getDesc().getNumOperands();
563 MachineOperand JTOp =
564 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
565 unsigned JTI = JTOp.getIndex();
566 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
567 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
568 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
569 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
570 DebugLoc(), TII->get(JTOpcode))
571 .addImm(i++)
572 .addJumpTableIndex(JTI)
573 .addImm(Size);
574 CPEMIs.push_back(CPEMI);
575 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
576 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
577 if (!LastCorrectlyNumberedBB)
578 LastCorrectlyNumberedBB = &MBB;
579 }
580
581 // If we did anything then we need to renumber the subsequent blocks.
582 if (LastCorrectlyNumberedBB)
583 MF->RenumberBlocks(LastCorrectlyNumberedBB);
584}
585
Dale Johannesene18b13b2007-02-23 05:02:36 +0000586/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000587/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000588bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000589 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000590 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000591 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000592 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000593 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000594
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000595 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000596 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000597 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000598
Tim Northoverab85dcc2014-11-13 17:58:51 +0000599 // Try to analyze the end of the block. A potential fallthrough may already
600 // have an unconditional branch for whatever reason.
601 MachineBasicBlock *TBB, *FBB;
602 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000603 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000604 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000605}
606
Evan Cheng8b7700f2007-02-09 20:54:44 +0000607/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
608/// look up the corresponding CPEntry.
609ARMConstantIslands::CPEntry
610*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
611 const MachineInstr *CPEMI) {
612 std::vector<CPEntry> &CPEs = CPEntries[CPI];
613 // Number of entries per constpool index should be small, just do a
614 // linear search.
615 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
616 if (CPEs[i].CPEMI == CPEMI)
617 return &CPEs[i];
618 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000619 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000620}
621
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000622/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000623/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000624unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000625 switch (CPEMI->getOpcode()) {
626 case ARM::CONSTPOOL_ENTRY:
627 break;
628 case ARM::JUMPTABLE_TBB:
James Molloy70a3d6d2016-11-01 13:37:41 +0000629 return isThumb1 ? 2 : 0;
Tim Northovera603c402015-05-31 19:22:07 +0000630 case ARM::JUMPTABLE_TBH:
James Molloy70a3d6d2016-11-01 13:37:41 +0000631 return isThumb1 ? 2 : 1;
Tim Northovera603c402015-05-31 19:22:07 +0000632 case ARM::JUMPTABLE_INSTS:
633 return 1;
634 case ARM::JUMPTABLE_ADDRS:
635 return 2;
636 default:
637 llvm_unreachable("unknown constpool entry kind");
638 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000639
Tim Northovera603c402015-05-31 19:22:07 +0000640 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000641 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
642 unsigned Align = MCP->getConstants()[CPI].getAlignment();
643 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
644 return Log2_32(Align);
645}
646
Jim Grosbach190e7b62012-03-23 23:07:03 +0000647/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000648/// information about the sizes of each block and the locations of all
649/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000650void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000651 for (MachineBasicBlock &MBB : *MF) {
652 for (MachineInstr &I : MBB)
James Molloy70a3d6d2016-11-01 13:37:41 +0000653 if (I.isBranch() &&
654 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000655 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000656 }
657}
658
Jim Grosbach190e7b62012-03-23 23:07:03 +0000659/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000660/// information about the sizes of each block, the location of all the water,
661/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000662void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000663initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000664
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000665 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000666
667 // The known bits of the entry block offset are determined by the function
668 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000669 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000670
671 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000672 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000673
Bill Wendling18581a42010-12-21 01:54:40 +0000674 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000675 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000676 // If this block doesn't fall through into the next MBB, then this is
677 // 'water' that a constant pool island could be placed.
678 if (!BBHasFallthrough(&MBB))
679 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000680
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000681 for (MachineInstr &I : MBB) {
682 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000683 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000684
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000685 unsigned Opc = I.getOpcode();
686 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000687 bool isCond = false;
688 unsigned Bits = 0;
689 unsigned Scale = 1;
690 int UOpc = Opc;
691 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000692 default:
693 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000694 case ARM::t2BR_JT:
James Molloy70a3d6d2016-11-01 13:37:41 +0000695 case ARM::tBR_JTr:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000696 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000697 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000698 case ARM::Bcc:
699 isCond = true;
700 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000701 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000702 case ARM::B:
703 Bits = 24;
704 Scale = 4;
705 break;
706 case ARM::tBcc:
707 isCond = true;
708 UOpc = ARM::tB;
709 Bits = 8;
710 Scale = 2;
711 break;
712 case ARM::tB:
713 Bits = 11;
714 Scale = 2;
715 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000716 case ARM::t2Bcc:
717 isCond = true;
718 UOpc = ARM::t2B;
719 Bits = 20;
720 Scale = 2;
721 break;
722 case ARM::t2B:
723 Bits = 24;
724 Scale = 2;
725 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000726 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000727
728 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000729 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000730 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000731 }
732
Evan Cheng7fa69642007-01-30 01:18:38 +0000733 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000734 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000735
Tim Northovera603c402015-05-31 19:22:07 +0000736 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
737 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
738 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000739 continue;
740
Evan Cheng10043e22007-01-19 07:51:42 +0000741 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000742 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
743 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000744 // We found one. The addressing mode tells us the max displacement
745 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000746
Evan Cheng10043e22007-01-19 07:51:42 +0000747 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000748 unsigned Bits = 0;
749 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000750 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000751 bool IsSoImm = false;
752
753 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000754 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000755 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000756
757 // Taking the address of a CP entry.
758 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000759 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000760 // This takes a SoImm, which is 8 bit immediate rotated. We'll
761 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000762 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000763 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000764 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000765 Scale = 4;
766 NegOk = true;
767 IsSoImm = true;
768 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000769 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000770 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000771 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000772 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000773 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000774 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000775 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000776 Bits = 8;
777 Scale = 4;
778 break;
779
David Majnemer452f1f92013-06-04 17:46:15 +0000780 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000781 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000782 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000783 case ARM::t2LDRpci:
James Molloy9abb2fa2016-09-26 07:26:24 +0000784 case ARM::t2LDRHpci:
Evan Chengfd522992007-02-01 20:44:52 +0000785 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000786 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000787 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000788
789 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000790 Bits = 8;
791 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000792 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000793
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000794 case ARM::VLDRD:
795 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000796 Bits = 8;
797 Scale = 4; // +-(offset_8*4)
798 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000799 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000800
801 case ARM::tLDRHi:
802 Bits = 5;
803 Scale = 2; // +(offset_5*2)
804 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000805 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000806
Evan Cheng10043e22007-01-19 07:51:42 +0000807 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000808 unsigned CPI = I.getOperand(op).getIndex();
809 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000810 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
811 CPI = JumpTableEntryIndices[CPI];
812 }
813
Evan Cheng8b7700f2007-02-09 20:54:44 +0000814 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000815 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000816 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000817
818 // Increment corresponding CPEntry reference count.
819 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
820 assert(CPE && "Cannot find a corresponding CPEntry!");
821 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000822
Evan Cheng10043e22007-01-19 07:51:42 +0000823 // Instructions can only use one CP entry, don't bother scanning the
824 // rest of the operands.
825 break;
826 }
827 }
Evan Cheng10043e22007-01-19 07:51:42 +0000828 }
829}
830
Jim Grosbach190e7b62012-03-23 23:07:03 +0000831/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000832/// from the start of the function. This offset changes as stuff is moved
833/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000834unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000835 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000836
Evan Cheng10043e22007-01-19 07:51:42 +0000837 // The offset is composed of two things: the sum of the sizes of all MBB's
838 // before this instruction's block, and the offset from the start of the block
839 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000840 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000841
842 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000843 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000844 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000845 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000846 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000847 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000848}
849
850/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
851/// ID.
852static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
853 const MachineBasicBlock *RHS) {
854 return LHS->getNumber() < RHS->getNumber();
855}
856
Jim Grosbach190e7b62012-03-23 23:07:03 +0000857/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000858/// machine function, it upsets all of the block numbers. Renumber the blocks
859/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000860void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000861 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000862 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000863
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000864 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000865 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000866 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000867
868 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000869 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000870 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000871 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
872 CompareMBBNumbers);
873 WaterList.insert(IP, NewBB);
874}
875
876
877/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000878/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000879/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000880MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000881 MachineBasicBlock *OrigBB = MI->getParent();
882
883 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000884 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000885 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000886 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000887 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000888
Evan Cheng10043e22007-01-19 07:51:42 +0000889 // Splice the instructions starting with MI over to NewBB.
890 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000891
Evan Cheng10043e22007-01-19 07:51:42 +0000892 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000893 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000894 // There doesn't seem to be meaningful DebugInfo available; this doesn't
895 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000896 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000897 if (!isThumb)
898 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
899 else
900 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
901 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000902 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000903
Evan Cheng10043e22007-01-19 07:51:42 +0000904 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000905 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000906
Evan Cheng10043e22007-01-19 07:51:42 +0000907 // OrigBB branches to NewBB.
908 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000909
Evan Cheng10043e22007-01-19 07:51:42 +0000910 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000911 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000912 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000913 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000914
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000915 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000916 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000917 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000918
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000919 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000920 // available water after it (but not if it's already there, which happens
921 // when splitting before a conditional branch that is followed by an
922 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000923 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000924 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
925 CompareMBBNumbers);
926 MachineBasicBlock* WaterBB = *IP;
927 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000928 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000929 else
930 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000931 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000932
Dale Johannesenc17dd572010-07-23 22:50:23 +0000933 // Figure out how large the OrigBB is. As the first half of the original
934 // block, it cannot contain a tablejump. The size includes
935 // the new jump we added. (It should be possible to do this without
936 // recounting everything, but it's very confusing, and this is rarely
937 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000938 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000939
Dale Johannesenc17dd572010-07-23 22:50:23 +0000940 // Figure out how large the NewMBB is. As the second half of the original
941 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000942 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000943
Dale Johannesen01ee5752007-02-25 00:47:03 +0000944 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000945 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000946
947 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000948}
949
Jim Grosbach190e7b62012-03-23 23:07:03 +0000950/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000951/// displacement computation. Update U.KnownAlignment to match its current
952/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000953unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
954 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000955 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
956 unsigned KnownBits = BBI.internalKnownBits();
957
958 // The value read from PC is offset from the actual instruction address.
959 UserOffset += (isThumb ? 4 : 8);
960
961 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
962 // Make sure U.getMaxDisp() returns a constrained range.
963 U.KnownAlignment = (KnownBits >= 2);
964
965 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
966 // purposes of the displacement computation; compensate for that here.
967 // For unknown alignments, getMaxDisp() constrains the range instead.
968 if (isThumb && U.KnownAlignment)
969 UserOffset &= ~3u;
970
971 return UserOffset;
972}
973
Jim Grosbach190e7b62012-03-23 23:07:03 +0000974/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000975/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000976/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000977/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000978/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
979/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000980bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000981 unsigned TrialOffset, unsigned MaxDisp,
982 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000983 if (UserOffset <= TrialOffset) {
984 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000985 if (TrialOffset - UserOffset <= MaxDisp)
986 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000987 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000988 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000989 if (UserOffset - TrialOffset <= MaxDisp)
990 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000991 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000992 }
993 return false;
994}
995
Jim Grosbach190e7b62012-03-23 23:07:03 +0000996/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000997/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000998///
999/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001000bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001001 MachineBasicBlock* Water, CPUser &U,
1002 unsigned &Growth) {
1003 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1004 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1005 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001006 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001007 if (++NextBlock == MF->end()) {
1008 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1009 NextBlockAlignment = 0;
1010 } else {
1011 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1012 NextBlockAlignment = NextBlock->getAlignment();
1013 }
1014 unsigned Size = U.CPEMI->getOperand(2).getImm();
1015 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001016
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001017 // The CPE may be able to hide in the alignment padding before the next
1018 // block. It may also cause more padding to be required if it is more aligned
1019 // that the next block.
1020 if (CPEEnd > NextBlockOffset) {
1021 Growth = CPEEnd - NextBlockOffset;
1022 // Compute the padding that would go at the end of the CPE to align the next
1023 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001024 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001025
1026 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001027 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001028 // in blocks between CPE and the user.
1029 if (CPEOffset < UserOffset)
1030 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1031 } else
1032 // CPE fits in existing padding.
1033 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001034
Jim Grosbach190e7b62012-03-23 23:07:03 +00001035 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001036}
1037
Jim Grosbach190e7b62012-03-23 23:07:03 +00001038/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001039/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001040bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001041 MachineInstr *CPEMI, unsigned MaxDisp,
1042 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001043 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001044
Dale Johannesene18b13b2007-02-23 05:02:36 +00001045 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001046 DEBUG({
1047 unsigned Block = MI->getParent()->getNumber();
1048 const BasicBlockInfo &BBI = BBInfo[Block];
1049 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1050 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001051 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001052 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001053 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1054 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1055 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001056 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001057 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001058
Jim Grosbach190e7b62012-03-23 23:07:03 +00001059 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001060}
1061
Evan Chenge4510972009-01-28 00:53:34 +00001062#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001063/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1064/// unconditionally branches to its only successor.
1065static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1066 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1067 return false;
1068
1069 MachineBasicBlock *Succ = *MBB->succ_begin();
1070 MachineBasicBlock *Pred = *MBB->pred_begin();
1071 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001072 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1073 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001074 return PredMI->getOperand(0).getMBB() == Succ;
1075 return false;
1076}
Evan Chenge4510972009-01-28 00:53:34 +00001077#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001078
Jim Grosbach190e7b62012-03-23 23:07:03 +00001079void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001080 unsigned BBNum = BB->getNumber();
1081 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001082 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001083 // Include the alignment of the current block.
1084 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1085 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1086 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001087
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001088 // This is where block i begins. Stop if the offset is already correct,
1089 // and we have updated 2 blocks. This is the maximum number of blocks
1090 // changed before calling this function.
1091 if (i > BBNum + 2 &&
1092 BBInfo[i].Offset == Offset &&
1093 BBInfo[i].KnownBits == KnownBits)
1094 break;
1095
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001096 BBInfo[i].Offset = Offset;
1097 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001098 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001099}
1100
Jim Grosbach190e7b62012-03-23 23:07:03 +00001101/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001102/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001103/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001104/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001105
Jim Grosbach190e7b62012-03-23 23:07:03 +00001106bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1107 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001108 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001109 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1110 assert(CPE && "Unexpected!");
1111 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001112 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001113 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001114 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001115 return true;
1116 }
1117 return false;
1118}
1119
Tim Northovera603c402015-05-31 19:22:07 +00001120unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1121 if (CPEMI->getOperand(1).isCPI())
1122 return CPEMI->getOperand(1).getIndex();
1123
1124 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1125}
1126
Dale Johannesene18b13b2007-02-23 05:02:36 +00001127/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1128/// if not, see if an in-range clone of the CPE is in range, and if so,
1129/// change the data structures so the user references the clone. Returns:
1130/// 0 = no existing entry found
1131/// 1 = entry found, and there were no code insertions or deletions
1132/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001133int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001134{
1135 MachineInstr *UserMI = U.MI;
1136 MachineInstr *CPEMI = U.CPEMI;
1137
1138 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001139 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1140 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001141 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001142 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001143 }
1144
Dale Johannesene18b13b2007-02-23 05:02:36 +00001145 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001146 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001147 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1148 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1149 // We already tried this one
1150 if (CPEs[i].CPEMI == CPEMI)
1151 continue;
1152 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001153 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001154 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001155 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001156 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001157 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001158 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001159 // Point the CPUser node to the replacement
1160 U.CPEMI = CPEs[i].CPEMI;
1161 // Change the CPI in the instruction operand to refer to the clone.
1162 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001163 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001164 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001165 break;
1166 }
1167 // Adjust the refcount of the clone...
1168 CPEs[i].RefCount++;
1169 // ...and the original. If we didn't remove the old entry, none of the
1170 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001171 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001172 }
1173 }
1174 return 0;
1175}
1176
Dale Johannesen440995b2007-02-28 18:41:23 +00001177/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1178/// the specific unconditional branch instruction.
1179static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001180 switch (Opc) {
1181 case ARM::tB:
1182 return ((1<<10)-1)*2;
1183 case ARM::t2B:
1184 return ((1<<23)-1)*2;
1185 default:
1186 break;
1187 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001188
David Goodwin27303cd2009-06-30 18:04:13 +00001189 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001190}
1191
Jim Grosbach190e7b62012-03-23 23:07:03 +00001192/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001193/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001194/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001195/// is set to the WaterList entry. For Thumb, prefer water that will not
1196/// introduce padding to water that will. To ensure that this pass
1197/// terminates, the CPE location for a particular CPUser is only allowed to
1198/// move to a lower address, so search backward from the end of the list and
1199/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001200bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001201 water_iterator &WaterIter,
1202 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001203 if (WaterList.empty())
1204 return false;
1205
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001206 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001207 // The nearest water without splitting the UserBB is right after it.
1208 // If the distance is still large (we have a big BB), then we need to split it
1209 // if we don't converge after certain iterations. This helps the following
1210 // situation to converge:
1211 // BB0:
1212 // Big BB
1213 // BB1:
1214 // Constant Pool
1215 // When a CP access is out of range, BB0 may be used as water. However,
1216 // inserting islands between BB0 and BB1 makes other accesses out of range.
1217 MachineBasicBlock *UserBB = U.MI->getParent();
1218 unsigned MinNoSplitDisp =
1219 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1220 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1221 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001222 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001223 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001224 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001225 // Check if water is in range and is either at a lower address than the
1226 // current "high water mark" or a new water block that was created since
1227 // the previous iteration by inserting an unconditional branch. In the
1228 // latter case, we want to allow resetting the high water mark back to
1229 // this new water since we haven't seen it before. Inserting branches
1230 // should be relatively uncommon and when it does happen, we want to be
1231 // sure to take advantage of it for all the CPEs near that block, so that
1232 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001233 // When CloserWater is true, we try to find the lowest address after (or
1234 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001235 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001236 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001237 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001238 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1239 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001240 // This is the least amount of required padding seen so far.
1241 BestGrowth = Growth;
1242 WaterIter = IP;
1243 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1244 << " Growth=" << Growth << '\n');
1245
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001246 if (CloserWater && WaterBB == U.MI->getParent())
1247 return true;
1248 // Keep looking unless it is perfect and we're not looking for the lowest
1249 // possible address.
1250 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001251 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001252 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001253 if (IP == B)
1254 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001255 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001256 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001257}
1258
Jim Grosbach190e7b62012-03-23 23:07:03 +00001259/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001260/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1261/// block is used if in range, and the conditional branch munged so control
1262/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001263/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001264/// block following which the new island can be inserted (the WaterList
1265/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001266void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001267 unsigned UserOffset,
1268 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001269 CPUser &U = CPUsers[CPUserIndex];
1270 MachineInstr *UserMI = U.MI;
1271 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001272 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001273 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001274 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001275
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001276 // If the block does not end in an unconditional branch already, and if the
1277 // end of the block is within range, make new water there. (The addition
1278 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001279 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001280 if (BBHasFallthrough(UserMBB)) {
1281 // Size of branch to insert.
1282 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001283 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001284 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001285
Jim Grosbach190e7b62012-03-23 23:07:03 +00001286 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001287 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1288 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001289 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001290 // Add an unconditional branch from UserMBB to fallthrough block. Record
1291 // it for branch lengthening; this new branch will not get out of range,
1292 // but if the preceding conditional branch is out of range, the targets
1293 // will be exchanged, and the altered branch may be out of range, so the
1294 // machinery has to know about it.
1295 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1296 if (!isThumb)
1297 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1298 else
1299 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1300 .addImm(ARMCC::AL).addReg(0);
1301 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1302 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1303 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001304 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001305 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001306 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001307 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001308 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001309
1310 // What a big block. Find a place within the block to split it. This is a
1311 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1312 // entries are 4 bytes: if instruction I references island CPE, and
1313 // instruction I+1 references CPE', it will not work well to put CPE as far
1314 // forward as possible, since then CPE' cannot immediately follow it (that
1315 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1316 // need to create a new island. So, we make a first guess, then walk through
1317 // the instructions between the one currently being looked at and the
1318 // possible insertion point, and make sure any other instructions that
1319 // reference CPEs will be able to use the same island area; if not, we back
1320 // up the insertion point.
1321
1322 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001323 // point where we can add a 4-byte branch instruction, and then align to
1324 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001325 unsigned LogAlign = MF->getAlignment();
1326 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1327 unsigned KnownBits = UserBBI.internalKnownBits();
1328 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001329 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001330 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1331 BaseInsertOffset));
1332
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001333 // The 4 in the following is for the unconditional branch we'll be inserting
1334 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001335 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001336 BaseInsertOffset -= 4;
1337
1338 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1339 << " la=" << LogAlign
1340 << " kb=" << KnownBits
1341 << " up=" << UPad << '\n');
1342
1343 // This could point off the end of the block if we've already got constant
1344 // pool entries following this block; only the last one is in the water list.
1345 // Back past any possible branches (allow for a conditional and a maximally
1346 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001347 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001348 // Ensure BaseInsertOffset is larger than the offset of the instruction
1349 // following UserMI so that the loop which searches for the split point
1350 // iterates at least once.
1351 BaseInsertOffset =
1352 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001353 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001354 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1355 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001356 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001357 CPEMI->getOperand(2).getImm();
1358 MachineBasicBlock::iterator MI = UserMI;
1359 ++MI;
1360 unsigned CPUIndex = CPUserIndex+1;
1361 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001362 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001363 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001364 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001365 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001366 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001367 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001368 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001369 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001370 // Shift intertion point by one unit of alignment so it is within reach.
1371 BaseInsertOffset -= 1u << LogAlign;
1372 EndInsertOffset -= 1u << LogAlign;
1373 }
1374 // This is overly conservative, as we don't account for CPEMIs being
1375 // reused within the block, but it doesn't matter much. Also assume CPEs
1376 // are added in order with alignment padding. We may eventually be able
1377 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001378 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001379 CPUIndex++;
1380 }
1381
1382 // Remember the last IT instruction.
1383 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001384 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001385 }
1386
1387 --MI;
1388
1389 // Avoid splitting an IT block.
1390 if (LastIT) {
1391 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001392 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001393 if (CC != ARMCC::AL)
1394 MI = LastIT;
1395 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001396
1397 // We really must not split an IT block.
1398 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001399 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001400
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001401 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001402}
1403
Jim Grosbach190e7b62012-03-23 23:07:03 +00001404/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001405/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001406/// place in-range. Return true if we changed any addresses (thus must run
1407/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001408bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1409 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001410 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001411 MachineInstr *UserMI = U.MI;
1412 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001413 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001414 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001415 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001416 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001417
Dale Johannesene18b13b2007-02-23 05:02:36 +00001418 // See if the current entry is within range, or there is a clone of it
1419 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001420 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001421 if (result==1) return false;
1422 else if (result==2) return true;
1423
1424 // No existing clone of this CPE is within range.
1425 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001426 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001427
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001428 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001429 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001430 MachineBasicBlock *NewMBB;
1431 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001432 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001433 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001434 MachineBasicBlock *WaterBB = *IP;
1435
1436 // If the original WaterList entry was "new water" on this iteration,
1437 // propagate that to the new island. This is just keeping NewWaterList
1438 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001439 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001440 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001441
Bob Wilson2f9be502009-10-15 20:49:47 +00001442 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001443 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001444 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001445 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001446 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001447 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001448
Jim Grosbach190e7b62012-03-23 23:07:03 +00001449 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001450 // called while handling branches so that the water will be seen on the
1451 // next iteration for constant pools, but in this context, we don't want
1452 // it. Check for this so it will be removed from the WaterList.
1453 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001454 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001455 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001456 if (IP != WaterList.end())
1457 NewWaterList.erase(WaterBB);
1458
1459 // We are adding new water. Update NewWaterList.
1460 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001461 }
1462
Bob Wilson2f9be502009-10-15 20:49:47 +00001463 // Remove the original WaterList entry; we want subsequent insertions in
1464 // this vicinity to go after the one we're about to insert. This
1465 // considerably reduces the number of times we have to move the same CPE
1466 // more than once and is also important to ensure the algorithm terminates.
1467 if (IP != WaterList.end())
1468 WaterList.erase(IP);
1469
Dale Johannesene18b13b2007-02-23 05:02:36 +00001470 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001471 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001472
1473 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001474 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001475
Dale Johannesene18b13b2007-02-23 05:02:36 +00001476 // Now that we have an island to add the CPE to, clone the original CPE and
1477 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001478 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001479 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1480 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001481 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001482 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001483
Tim Northovera603c402015-05-31 19:22:07 +00001484 // Decrement the old entry, and remove it if refcount becomes 0.
1485 decrementCPEReferenceCount(CPI, CPEMI);
1486
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001487 // Mark the basic block as aligned as required by the const-pool entry.
1488 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001489
Evan Cheng10043e22007-01-19 07:51:42 +00001490 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001491 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001492 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001493
Evan Cheng10043e22007-01-19 07:51:42 +00001494 // Finally, change the CPI in the instruction operand to be ID.
1495 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001496 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001497 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001498 break;
1499 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001500
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001501 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001502 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001503
Evan Cheng10043e22007-01-19 07:51:42 +00001504 return true;
1505}
1506
Jim Grosbach190e7b62012-03-23 23:07:03 +00001507/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001508/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001509void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001510 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001511 unsigned Size = CPEMI->getOperand(2).getImm();
1512 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001513 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001514 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001515 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001516 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001517
Evan Chengab28b9a2013-02-21 18:37:54 +00001518 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001519 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001520 } else
1521 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001522 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001523
Jim Grosbach190e7b62012-03-23 23:07:03 +00001524 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001525 // An island has only one predecessor BB and one successor BB. Check if
1526 // this BB's predecessor jumps directly to this BB's successor. This
1527 // shouldn't happen currently.
1528 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1529 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001530}
1531
Jim Grosbach190e7b62012-03-23 23:07:03 +00001532/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001533/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001534bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001535 unsigned MadeChange = false;
1536 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1537 std::vector<CPEntry> &CPEs = CPEntries[i];
1538 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1539 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001540 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001541 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001542 MadeChange = true;
1543 }
1544 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001545 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001546 return MadeChange;
1547}
1548
Jim Grosbach190e7b62012-03-23 23:07:03 +00001549/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001550/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001551bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001552 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001553 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001554 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001555 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001556
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001557 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001558 << " from BB#" << MI->getParent()->getNumber()
1559 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001560 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001561 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001562
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001563 if (BrOffset <= DestOffset) {
1564 // Branch before the Dest.
1565 if (DestOffset-BrOffset <= MaxDisp)
1566 return true;
1567 } else {
1568 if (BrOffset-DestOffset <= MaxDisp)
1569 return true;
1570 }
1571 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001572}
1573
Jim Grosbach190e7b62012-03-23 23:07:03 +00001574/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001575/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001576bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001577 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001578 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001579
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001580 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001581 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001582 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001583
Evan Cheng7fa69642007-01-30 01:18:38 +00001584 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001585 return fixupUnconditionalBr(Br);
1586 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001587}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001588
Jim Grosbach190e7b62012-03-23 23:07:03 +00001589/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001590/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001591/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001592/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001593bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001594ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001595 MachineInstr *MI = Br.MI;
1596 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001597 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001598 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001599
1600 // Use BL to implement far jump.
1601 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001602 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001603 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001604 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001605 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001606 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001607
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001608 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001609
Evan Cheng7fa69642007-01-30 01:18:38 +00001610 return true;
1611}
1612
Jim Grosbach190e7b62012-03-23 23:07:03 +00001613/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001614/// far away to fit in its displacement field. It is converted to an inverse
1615/// conditional branch + an unconditional branch to the destination.
1616bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001617ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001618 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001619 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001620
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001621 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001622 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001623 // blt L1
1624 // =>
1625 // bge L2
1626 // b L1
1627 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001628 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001629 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001630 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001631
1632 // If the branch is at the end of its MBB and that has a fall-through block,
1633 // direct the updated conditional branch to the fall-through block. Otherwise,
1634 // split the MBB before the next instruction.
1635 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001636 MachineInstr *BMI = &MBB->back();
1637 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001638
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001639 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001640 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001641 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001642 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001643 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001644 // condition and swap destinations:
1645 // beq L1
1646 // b L2
1647 // =>
1648 // bne L2
1649 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001650 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001651 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001652 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001653 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001654 BMI->getOperand(0).setMBB(DestBB);
1655 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001656 MI->getOperand(1).setImm(CC);
1657 return true;
1658 }
1659 }
1660 }
1661
1662 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001663 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001664 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001665 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001666 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001667 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001668 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001669 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001670 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001671 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001672
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001673 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001674 << " also invert condition and change dest. to BB#"
1675 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001676
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001677 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001678 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001679 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001680 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001681 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001682 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001683 if (isThumb)
1684 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1685 .addImm(ARMCC::AL).addReg(0);
1686 else
1687 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001688 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001689 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001690 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001691
1692 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001693 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001694 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001695 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001696 return true;
1697}
Evan Cheng7fa69642007-01-30 01:18:38 +00001698
Jim Grosbach190e7b62012-03-23 23:07:03 +00001699/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001700/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1701/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001702bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001703 bool MadeChange = false;
1704 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1705 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001706 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001707 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001708 MI->getOperand(2).getReg() == ARM::PC &&
1709 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001710 // Create the new insn and copy the predicate from the old.
1711 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1712 .addOperand(MI->getOperand(0))
1713 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001714 MI->eraseFromParent();
1715 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001716 }
1717 }
1718 return MadeChange;
1719}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001720
Jim Grosbach190e7b62012-03-23 23:07:03 +00001721bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001722 bool MadeChange = false;
1723
1724 // Shrink ADR and LDR from constantpool.
1725 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1726 CPUser &U = CPUsers[i];
1727 unsigned Opcode = U.MI->getOpcode();
1728 unsigned NewOpc = 0;
1729 unsigned Scale = 1;
1730 unsigned Bits = 0;
1731 switch (Opcode) {
1732 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001733 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001734 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1735 NewOpc = ARM::tLEApcrel;
1736 Bits = 8;
1737 Scale = 4;
1738 }
1739 break;
1740 case ARM::t2LDRpci:
1741 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1742 NewOpc = ARM::tLDRpci;
1743 Bits = 8;
1744 Scale = 4;
1745 }
1746 break;
1747 }
1748
1749 if (!NewOpc)
1750 continue;
1751
Jim Grosbach190e7b62012-03-23 23:07:03 +00001752 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001753 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001754
1755 // Be conservative with inline asm.
1756 if (!U.KnownAlignment)
1757 MaxOffs -= 2;
1758
Evan Chengdb73d682009-08-14 00:32:16 +00001759 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001760 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001761 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001762 U.MI->setDesc(TII->get(NewOpc));
1763 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001764 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001765 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001766 ++NumT2CPShrunk;
1767 MadeChange = true;
1768 }
1769 }
1770
Evan Chengdb73d682009-08-14 00:32:16 +00001771 return MadeChange;
1772}
1773
Jim Grosbach190e7b62012-03-23 23:07:03 +00001774bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001775 bool MadeChange = false;
1776
Peter Collingbourne167668f2015-04-23 20:31:35 +00001777 // The order in which branches appear in ImmBranches is approximately their
1778 // order within the function body. By visiting later branches first, we reduce
1779 // the distance between earlier forward branches and their targets, making it
1780 // more likely that the cbn?z optimization, which can only apply to forward
1781 // branches, will succeed.
1782 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1783 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001784 unsigned Opcode = Br.MI->getOpcode();
1785 unsigned NewOpc = 0;
1786 unsigned Scale = 1;
1787 unsigned Bits = 0;
1788 switch (Opcode) {
1789 default: break;
1790 case ARM::t2B:
1791 NewOpc = ARM::tB;
1792 Bits = 11;
1793 Scale = 2;
1794 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001795 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001796 NewOpc = ARM::tBcc;
1797 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001798 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001799 break;
1800 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001801 }
1802 if (NewOpc) {
1803 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1804 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001805 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001806 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001807 Br.MI->setDesc(TII->get(NewOpc));
1808 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001809 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001810 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001811 ++NumT2BrShrunk;
1812 MadeChange = true;
1813 }
1814 }
1815
1816 Opcode = Br.MI->getOpcode();
1817 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001818 continue;
1819
Evan Cheng6bb95252012-01-14 01:53:46 +00001820 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1821 // so this transformation is not safe.
1822 if (!Br.MI->killsRegister(ARM::CPSR))
1823 continue;
1824
Evan Cheng6f29ad92009-10-31 23:46:45 +00001825 NewOpc = 0;
1826 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001827 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001828 if (Pred == ARMCC::EQ)
1829 NewOpc = ARM::tCBZ;
1830 else if (Pred == ARMCC::NE)
1831 NewOpc = ARM::tCBNZ;
1832 if (!NewOpc)
1833 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001834 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001835 // Check if the distance is within 126. Subtract starting offset by 2
1836 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001837 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001838 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001839 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001840 MachineBasicBlock::iterator CmpMI = Br.MI;
1841 if (CmpMI != Br.MI->getParent()->begin()) {
1842 --CmpMI;
1843 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1844 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001845 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001846 if (Pred == ARMCC::AL &&
1847 CmpMI->getOperand(1).getImm() == 0 &&
1848 isARMLowRegister(Reg)) {
1849 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001850 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001851 MachineInstr *NewBR =
1852 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1853 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1854 CmpMI->eraseFromParent();
1855 Br.MI->eraseFromParent();
1856 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001857 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001858 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001859 ++NumCBZ;
1860 MadeChange = true;
1861 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001862 }
1863 }
Evan Chenge41903b2009-08-14 18:31:44 +00001864 }
1865 }
1866
1867 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001868}
1869
Tim Northovera603c402015-05-31 19:22:07 +00001870static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1871 unsigned BaseReg) {
1872 if (I.getOpcode() != ARM::t2ADDrs)
1873 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001874
Tim Northovera603c402015-05-31 19:22:07 +00001875 if (I.getOperand(0).getReg() != EntryReg)
1876 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001877
Tim Northovera603c402015-05-31 19:22:07 +00001878 if (I.getOperand(1).getReg() != BaseReg)
1879 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001880
Tim Northovera603c402015-05-31 19:22:07 +00001881 // FIXME: what about CC and IdxReg?
1882 return true;
1883}
Tim Northover688f7bb2015-05-13 20:28:32 +00001884
Tim Northovera603c402015-05-31 19:22:07 +00001885/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1886/// doesn't immediately follow the BR_JT) need access to the start of the
1887/// jump-table. We know one instruction that produces such a register; this
1888/// function works out whether that definition can be preserved to the BR_JT,
1889/// possibly by removing an intervening addition (which is usually needed to
1890/// calculate the actual entry to jump to).
1891bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1892 MachineInstr *LEAMI,
1893 unsigned &DeadSize,
1894 bool &CanDeleteLEA,
1895 bool &BaseRegKill) {
1896 if (JumpMI->getParent() != LEAMI->getParent())
1897 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001898
Tim Northovera603c402015-05-31 19:22:07 +00001899 // Now we hope that we have at least these instructions in the basic block:
1900 // BaseReg = t2LEA ...
1901 // [...]
1902 // EntryReg = t2ADDrs BaseReg, ...
1903 // [...]
1904 // t2BR_JT EntryReg
1905 //
1906 // We have to be very conservative about what we recognise here though. The
1907 // main perturbing factors to watch out for are:
1908 // + Spills at any point in the chain: not direct problems but we would
1909 // expect a blocking Def of the spilled register so in practice what we
1910 // can do is limited.
1911 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1912 // of BaseReg, but only if the t2ADDrs can be removed.
1913 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1914 // the wild, but we should be careful.
1915 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1916 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1917
1918 CanDeleteLEA = true;
1919 BaseRegKill = false;
1920 MachineInstr *RemovableAdd = nullptr;
1921 MachineBasicBlock::iterator I(LEAMI);
1922 for (++I; &*I != JumpMI; ++I) {
1923 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1924 RemovableAdd = &*I;
1925 break;
1926 }
1927
1928 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1929 const MachineOperand &MO = I->getOperand(K);
1930 if (!MO.isReg() || !MO.getReg())
1931 continue;
1932 if (MO.isDef() && MO.getReg() == BaseReg)
1933 return false;
1934 if (MO.isUse() && MO.getReg() == BaseReg) {
1935 BaseRegKill = BaseRegKill || MO.isKill();
1936 CanDeleteLEA = false;
1937 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001938 }
1939 }
1940
Tim Northovera603c402015-05-31 19:22:07 +00001941 if (!RemovableAdd)
1942 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001943
Tim Northovera603c402015-05-31 19:22:07 +00001944 // Check the add really is removable, and that nothing else in the block
1945 // clobbers BaseReg.
1946 for (++I; &*I != JumpMI; ++I) {
1947 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1948 const MachineOperand &MO = I->getOperand(K);
1949 if (!MO.isReg() || !MO.getReg())
1950 continue;
1951 if (MO.isDef() && MO.getReg() == BaseReg)
1952 return false;
1953 if (MO.isUse() && MO.getReg() == EntryReg)
1954 RemovableAdd = nullptr;
1955 }
1956 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001957
Tim Northovera603c402015-05-31 19:22:07 +00001958 if (RemovableAdd) {
1959 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00001960 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00001961 } else if (BaseReg == EntryReg) {
1962 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1963 // preserve it.
1964 return false;
1965 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001966
Tim Northovera603c402015-05-31 19:22:07 +00001967 // We reached the end of the block without seeing another definition of
1968 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
1969 // used in the TBB/TBH if necessary.
1970 return true;
1971}
Tim Northover688f7bb2015-05-13 20:28:32 +00001972
Tim Northovera603c402015-05-31 19:22:07 +00001973/// \brief Returns whether CPEMI is the first instruction in the block
1974/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
1975/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001976/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00001977static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001978 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00001979 MachineFunction *MF = MBB->getParent();
1980 ++MBB;
1981
1982 return MBB != MF->end() && MBB->begin() != MBB->end() &&
1983 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00001984}
1985
Jim Grosbach190e7b62012-03-23 23:07:03 +00001986/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001987/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001988bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001989 bool MadeChange = false;
1990
1991 // FIXME: After the tables are shrunk, can we get rid some of the
1992 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001993 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001994 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001995
Evan Chengc6d70ae2009-07-29 02:18:14 +00001996 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1997 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1998 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001999 const MCInstrDesc &MCID = MI->getDesc();
2000 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002001 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002002 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2003 unsigned JTI = JTOP.getIndex();
2004 assert(JTI < JT.size());
2005
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002006 bool ByteOk = true;
2007 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002008 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002009 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002010 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2011 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002012 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002013 // Negative offset is not ok. FIXME: We should change BB layout to make
2014 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002015 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002016 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002017 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002018 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002019 HalfWordOk = false;
2020 if (!ByteOk && !HalfWordOk)
2021 break;
2022 }
2023
Tim Northovera603c402015-05-31 19:22:07 +00002024 if (!ByteOk && !HalfWordOk)
2025 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002026
James Molloy70a3d6d2016-11-01 13:37:41 +00002027 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002028 MachineBasicBlock *MBB = MI->getParent();
2029 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2030 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002031
Tim Northovera603c402015-05-31 19:22:07 +00002032 unsigned DeadSize = 0;
2033 bool CanDeleteLEA = false;
2034 bool BaseRegKill = false;
James Molloy70a3d6d2016-11-01 13:37:41 +00002035
2036 unsigned IdxReg = ~0U;
2037 bool IdxRegKill = true;
2038 if (isThumb2) {
2039 IdxReg = MI->getOperand(1).getReg();
2040 IdxRegKill = MI->getOperand(1).isKill();
2041
2042 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002043 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002044 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2045 continue;
2046 } else {
2047 // We're in thumb-1 mode, so we must have something like:
2048 // %idx = tLSLri %idx, 2
2049 // %base = tLEApcrelJT
2050 // %t = tLDRr %idx, %base
2051 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002052
James Molloy70a3d6d2016-11-01 13:37:41 +00002053 if (User.MI->getIterator() == User.MI->getParent()->begin())
2054 continue;
2055 MachineInstr *Shift = User.MI->getPrevNode();
2056 if (Shift->getOpcode() != ARM::tLSLri ||
2057 Shift->getOperand(3).getImm() != 2 ||
2058 !Shift->getOperand(2).isKill())
2059 continue;
2060 IdxReg = Shift->getOperand(2).getReg();
2061 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002062
James Molloy70a3d6d2016-11-01 13:37:41 +00002063 MachineInstr *Load = User.MI->getNextNode();
2064 if (Load->getOpcode() != ARM::tLDRr)
2065 continue;
2066 if (Load->getOperand(1).getReg() != ShiftedIdxReg ||
2067 Load->getOperand(2).getReg() != BaseReg ||
2068 !Load->getOperand(1).isKill())
2069 continue;
2070
2071 // If we're in PIC mode, there should be another ADD following.
2072 if (isPositionIndependentOrROPI) {
2073 MachineInstr *Add = Load->getNextNode();
2074 if (Add->getOpcode() != ARM::tADDrr ||
2075 Add->getOperand(2).getReg() != Load->getOperand(0).getReg() ||
2076 Add->getOperand(3).getReg() != BaseReg ||
2077 !Add->getOperand(2).isKill())
2078 continue;
2079 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2080 continue;
2081
2082 Add->eraseFromParent();
2083 DeadSize += 2;
2084 } else {
2085 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2086 continue;
2087 }
2088
2089
2090 // Now safe to delete the load and lsl. The LEA will be removed later.
2091 CanDeleteLEA = true;
2092 Shift->eraseFromParent();
2093 Load->eraseFromParent();
2094 DeadSize += 4;
2095 }
2096
Tim Northovera603c402015-05-31 19:22:07 +00002097 DEBUG(dbgs() << "Shrink JT: " << *MI);
2098 MachineInstr *CPEMI = User.CPEMI;
2099 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002100 if (!isThumb2)
2101 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2102
Tim Northovera603c402015-05-31 19:22:07 +00002103 MachineBasicBlock::iterator MI_JT = MI;
2104 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002105 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002106 .addReg(User.MI->getOperand(0).getReg(),
2107 getKillRegState(BaseRegKill))
2108 .addReg(IdxReg, getKillRegState(IdxRegKill))
2109 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2110 .addImm(CPEMI->getOperand(0).getImm());
2111 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002112
Tim Northovera603c402015-05-31 19:22:07 +00002113 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2114 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002115
Tim Northovera603c402015-05-31 19:22:07 +00002116 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2117 NewJTMI->getOperand(0).setReg(ARM::PC);
2118 NewJTMI->getOperand(0).setIsKill(false);
2119
2120 if (CanDeleteLEA) {
2121 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002122 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002123
2124 // The LEA was eliminated, the TBB instruction becomes the only new user
2125 // of the jump table.
2126 User.MI = NewJTMI;
2127 User.MaxDisp = 4;
2128 User.NegOk = false;
2129 User.IsSoImm = false;
2130 User.KnownAlignment = false;
2131 } else {
2132 // The LEA couldn't be eliminated, so we must add another CPUser to
2133 // record the TBB or TBH use.
2134 int CPEntryIdx = JumpTableEntryIndices[JTI];
2135 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002136 auto Entry =
2137 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002138 ++Entry->RefCount;
2139 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2140 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002141 }
Tim Northovera603c402015-05-31 19:22:07 +00002142
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002143 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2144 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002145 MI->eraseFromParent();
2146
2147 int Delta = OrigSize - NewSize + DeadSize;
2148 BBInfo[MBB->getNumber()].Size -= Delta;
2149 adjustBBOffsetsAfter(MBB);
2150
2151 ++NumTBs;
2152 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002153 }
2154
2155 return MadeChange;
2156}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002157
Jim Grosbach190e7b62012-03-23 23:07:03 +00002158/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002159/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002160bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002161 bool MadeChange = false;
2162
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002163 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002164 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002165
Jim Grosbach5d577142009-11-12 17:25:07 +00002166 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2167 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2168 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002169 const MCInstrDesc &MCID = MI->getDesc();
2170 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002171 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002172 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2173 unsigned JTI = JTOP.getIndex();
2174 assert(JTI < JT.size());
2175
2176 // We prefer if target blocks for the jump table come after the jump
2177 // instruction so we can use TB[BH]. Loop through the target blocks
2178 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002179 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002180 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2181 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2182 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002183 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002184
Jim Grosbach9785e592009-11-16 18:58:52 +00002185 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002186 // The destination precedes the switch. Try to move the block forward
2187 // so we have a positive offset.
2188 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002189 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002190 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002191 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002192 MadeChange = true;
2193 }
2194 }
2195 }
2196
2197 return MadeChange;
2198}
2199
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002200MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002201adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002202 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002203 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002204 // table that branches back to the actual target. This is a very simple
2205 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002206 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002207 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002208 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002209 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002210 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002211
Jim Grosbach47d5e332009-11-16 17:10:56 +00002212 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002213 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002214
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002215 // If the block ends in an unconditional branch, move it. The prior block
2216 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002217 // 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 +00002218 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002219 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002220 BB->moveAfter(JTBB);
2221 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002222 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002223 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002224 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002225 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002226 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002227 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002228
2229 // Create a new MBB for the code after the jump BB.
2230 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002231 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002232 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002233 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002234
2235 // Add an unconditional branch from NewBB to BB.
2236 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2237 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002238 if (isThumb2)
2239 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2240 .addMBB(BB)
2241 .addImm(ARMCC::AL)
2242 .addReg(0);
2243 else
2244 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2245 .addMBB(BB)
2246 .addImm(ARMCC::AL)
2247 .addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002248
Jim Grosbach43d21082009-11-14 20:10:18 +00002249 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002250 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002251
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002252 // Update the CFG.
2253 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002254 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002255
Jim Grosbach5d577142009-11-12 17:25:07 +00002256 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002257 return NewBB;
2258}