blob: ab25b01a5403bdd595f7326eeacce6a2bab9a126 [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
Evan Cheng10043e22007-01-19 07:51:42 +000061namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000062 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000063 /// requires constant pool entries to be scattered among the instructions
64 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000065 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000066 /// special instructions.
67 ///
68 /// The terminology used in this pass includes:
69 /// Islands - Clumps of constants placed in the function.
70 /// Water - Potential places where an island could be formed.
71 /// CPE - A constant pool entry that has been placed somewhere, which
72 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000073 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000074
75 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +000076
Evan Cheng10043e22007-01-19 07:51:42 +000077 /// WaterList - A sorted list of basic blocks where islands could be placed
78 /// (i.e. blocks that don't fall through to the following block, due
79 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +000080 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +000081
Bob Wilson2f9be502009-10-15 20:49:47 +000082 /// NewWaterList - The subset of WaterList that was created since the
83 /// previous iteration by inserting unconditional branches.
84 SmallSet<MachineBasicBlock*, 4> NewWaterList;
85
Bob Wilsonc7a3cf42009-10-12 18:52:13 +000086 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
87
Evan Cheng10043e22007-01-19 07:51:42 +000088 /// CPUser - One user of a constant pool, keeping the machine instruction
89 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +000090 /// allowed from the instruction to the CP. The HighWaterMark records the
91 /// highest basic block where a new CPEntry can be placed. To ensure this
92 /// pass terminates, the CP entries are initially placed at the end of the
93 /// function and then move monotonically to lower addresses. The
94 /// exception to this rule is when the current CP entry for a particular
95 /// CPUser is out of range, but there is another CP entry for the same
96 /// constant value in range. We want to use the existing in-range CP
97 /// entry, but if it later moves out of range, the search for new water
98 /// should resume where it left off. The HighWaterMark is used to record
99 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000100 struct CPUser {
101 MachineInstr *MI;
102 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000103 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000104 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000105 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000106 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000107 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
111 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000112 HighWaterMark = CPEMI->getParent();
113 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000114 /// getMaxDisp - Returns the maximum displacement supported by MI.
115 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000116 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000117 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000118 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000119 }
Evan Cheng10043e22007-01-19 07:51:42 +0000120 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000121
Evan Cheng10043e22007-01-19 07:51:42 +0000122 /// CPUsers - Keep track of all of the machine instructions that use various
123 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000124 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000125
Evan Cheng8b7700f2007-02-09 20:54:44 +0000126 /// CPEntry - One per constant pool entry, keeping the machine instruction
127 /// pointer, the constpool index, and the number of CPUser's which
128 /// reference this entry.
129 struct CPEntry {
130 MachineInstr *CPEMI;
131 unsigned CPI;
132 unsigned RefCount;
133 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
134 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
135 };
136
137 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000138 /// instructions. For each original constpool index (i.e. those that existed
139 /// upon entry to this pass), it keeps a vector of entries. Original
140 /// elements are cloned as we go along; the clones are put in the vector of
141 /// the original element, but have distinct CPIs.
142 ///
143 /// The first half of CPEntries contains generic constants, the second half
144 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
145 /// which vector it will be in here.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000146 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000147
Tim Northovera603c402015-05-31 19:22:07 +0000148 /// Maps a JT index to the offset in CPEntries containing copies of that
149 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
150 DenseMap<int, int> JumpTableEntryIndices;
151
152 /// Maps a JT index to the LEA that actually uses the index to calculate its
153 /// base address.
154 DenseMap<int, int> JumpTableUserIndices;
155
Evan Cheng22c7cf52007-01-25 03:12:46 +0000156 /// ImmBranch - One per immediate branch, keeping the machine instruction
157 /// pointer, conditional or unconditional, the max displacement,
158 /// and (if isCond is true) the corresponding unconditional branch
159 /// opcode.
160 struct ImmBranch {
161 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000162 unsigned MaxDisp : 31;
163 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000164 unsigned UncondBr;
165 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000166 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000167 };
168
Evan Chengc95f95b2007-05-16 05:14:06 +0000169 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000170 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000171 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000172
Evan Cheng7fa69642007-01-30 01:18:38 +0000173 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
174 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000175 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000176
Evan Chengc6d70ae2009-07-29 02:18:14 +0000177 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
178 SmallVector<MachineInstr*, 4> T2JumpTables;
179
Evan Cheng7fa69642007-01-30 01:18:38 +0000180 /// HasFarJump - True if any far jump instruction has been emitted during
181 /// the branch fix up pass.
182 bool HasFarJump;
183
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000184 MachineFunction *MF;
185 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000186 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000187 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000188 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000189 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000190 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000191 bool isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +0000192 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000193 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000194 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000195
Craig Topper6bc27bf2014-03-10 02:09:33 +0000196 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000197
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000198 MachineFunctionProperties getRequiredProperties() const override {
199 return MachineFunctionProperties().set(
200 MachineFunctionProperties::Property::AllVRegsAllocated);
201 }
202
Craig Topper6bc27bf2014-03-10 02:09:33 +0000203 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000204 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000205 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000206
Evan Cheng10043e22007-01-19 07:51:42 +0000207 private:
Tim Northovera603c402015-05-31 19:22:07 +0000208 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
209 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000210 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000211 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000212 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000213 void scanFunctionJumpTables();
214 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
215 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
216 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
217 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
218 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000219 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000220 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
221 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000222 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000223 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000224 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000225 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000226 void removeDeadCPEMI(MachineInstr *CPEMI);
227 bool removeUnusedCPEntries();
228 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
229 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
230 bool DoDump = false);
231 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000232 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000233 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
234 bool fixupImmediateBr(ImmBranch &Br);
235 bool fixupConditionalBr(ImmBranch &Br);
236 bool fixupUnconditionalBr(ImmBranch &Br);
237 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000238 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000239 bool optimizeThumb2Instructions();
240 bool optimizeThumb2Branches();
241 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000242 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
243 unsigned &DeadSize, bool &CanDeleteLEA,
244 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000245 bool optimizeThumb2JumpTables();
246 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000247 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000248
Jim Grosbach190e7b62012-03-23 23:07:03 +0000249 unsigned getOffsetOf(MachineInstr *MI) const;
250 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000251 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000252 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000253
Jim Grosbach190e7b62012-03-23 23:07:03 +0000254 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000255 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000256 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000257 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000258 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000259 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000260 }
Evan Cheng10043e22007-01-19 07:51:42 +0000261 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000262 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000263}
Evan Cheng10043e22007-01-19 07:51:42 +0000264
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000265/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000266void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000267#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000268 assert(std::is_sorted(MF->begin(), MF->end(),
269 [this](const MachineBasicBlock &LHS,
270 const MachineBasicBlock &RHS) {
271 return BBInfo[LHS.getNumber()].postOffset() <
272 BBInfo[RHS.getNumber()].postOffset();
273 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000274 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000275 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
276 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000277 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000278 // Verify offset using the real max displacement without the safety
279 // adjustment.
280 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000281 /* DoDump = */ true)) {
282 DEBUG(dbgs() << "OK\n");
283 continue;
284 }
285 DEBUG(dbgs() << "Out of range.\n");
286 dumpBBs();
287 DEBUG(MF->dump());
288 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000289 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000290#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000291}
292
293/// print block size and offset information - debugging
294void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000295 DEBUG({
296 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
297 const BasicBlockInfo &BBI = BBInfo[J];
298 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
299 << " kb=" << unsigned(BBI.KnownBits)
300 << " ua=" << unsigned(BBI.Unalign)
301 << " pa=" << unsigned(BBI.PostAlign)
302 << format(" size=%#x\n", BBInfo[J].Size);
303 }
304 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000305}
306
Evan Cheng22c7cf52007-01-25 03:12:46 +0000307/// createARMConstantIslandPass - returns an instance of the constpool
308/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000309FunctionPass *llvm::createARMConstantIslandPass() {
310 return new ARMConstantIslands();
311}
312
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000313bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
314 MF = &mf;
315 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000316
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000317 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000318 << MCP->getConstants().size() << " CP entries, aligned to "
319 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000320
Eric Christopher1b21f002015-01-29 00:19:33 +0000321 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
322 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000323 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000324
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000325 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000326 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000327 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000328
329 HasFarJump = false;
330
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000331 // This pass invalidates liveness information when it splits basic blocks.
332 MF->getRegInfo().invalidateLiveness();
333
Evan Cheng10043e22007-01-19 07:51:42 +0000334 // Renumber all of the machine basic blocks in the function, guaranteeing that
335 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000336 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000337
Jim Grosbach5d577142009-11-12 17:25:07 +0000338 // Try to reorder and otherwise adjust the block layout to make good use
339 // of the TB[BH] instructions.
340 bool MadeChange = false;
341 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000342 scanFunctionJumpTables();
343 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000344 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000345 T2JumpTables.clear();
346 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000347 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000348 }
349
Evan Cheng10043e22007-01-19 07:51:42 +0000350 // Perform the initial placement of the constant pool entries. To start with,
351 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000352 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000353 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000354 doInitialConstPlacement(CPEMIs);
355
356 if (MF->getJumpTableInfo())
357 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000358
Evan Cheng10043e22007-01-19 07:51:42 +0000359 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000360 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000361
Evan Cheng10043e22007-01-19 07:51:42 +0000362 // Do the initial scan of the function, building up information about the
363 // sizes of each block, the location of all the water, and finding all of the
364 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000365 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000366 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000367 DEBUG(dumpBBs());
368
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000369 // Functions with jump tables need an alignment of 4 because they use the ADR
370 // instruction, which aligns the PC to 4 bytes before adding an offset.
371 if (!T2JumpTables.empty())
372 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000373
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000374 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000375 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000376
Evan Cheng7fa69642007-01-30 01:18:38 +0000377 // Iteratively place constant pool entries and fix up branches until there
378 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000379 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000380 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000381 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000382 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000383 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000384 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000385 // If it doesn't end in 10, the input may have huge BB or many CPEs.
386 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000387 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
388 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000389 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000390 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000391
Bob Wilson2f9be502009-10-15 20:49:47 +0000392 // Clear NewWaterList now. If we split a block for branches, it should
393 // appear as "new water" for the next iteration of constant pool placement.
394 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000395
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000396 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000397 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000398 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000399 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000400 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000401 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000402 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000403
404 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000405 break;
406 MadeChange = true;
407 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000408
Bradley Smitha1189102016-01-15 10:26:17 +0000409 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000410 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000411 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000412
Bradley Smitha1189102016-01-15 10:26:17 +0000413 // Shrink 32-bit branch instructions.
414 if (isThumb && STI->hasV8MBaselineOps())
415 MadeChange |= optimizeThumb2Branches();
416
417 // Optimize jump tables using TBB / TBH.
418 if (isThumb2)
419 MadeChange |= optimizeThumb2JumpTables();
420
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000421 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000422 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000423
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000424 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
425 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000426 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000427 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000428
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000429 // Save the mapping between original and cloned constpool entries.
430 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
431 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
432 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000433 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
434 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000435 }
436 }
437
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000438 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000439
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000440 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000441 WaterList.clear();
442 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000443 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000444 JumpTableEntryIndices.clear();
445 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000446 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000447 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000448 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000449
450 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000451}
452
Tim Northovera603c402015-05-31 19:22:07 +0000453/// \brief Perform the initial placement of the regular constant pool entries.
454/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000455void
Tim Northovera603c402015-05-31 19:22:07 +0000456ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000457 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000458 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
459 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000460
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000461 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000462 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000463
464 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000465 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000466
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000467 // The function needs to be as aligned as the basic blocks. The linker may
468 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000469 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000470
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000471 // Order the entries in BB by descending alignment. That ensures correct
472 // alignment of all entries as long as BB is sufficiently aligned. Keep
473 // track of the insertion point for each alignment. We are going to bucket
474 // sort the entries as they are created.
475 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000476
Evan Cheng10043e22007-01-19 07:51:42 +0000477 // Add all of the constants from the constant pool to the end block, use an
478 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000479 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000480
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000481 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000482 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000483 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000484 assert(Size >= 4 && "Too small constant pool entry");
485 unsigned Align = CPs[i].getAlignment();
486 assert(isPowerOf2_32(Align) && "Invalid alignment");
487 // Verify that all constant pool entries are a multiple of their alignment.
488 // If not, we would have to pad them out so that instructions stay aligned.
489 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
490
491 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
492 unsigned LogAlign = Log2_32(Align);
493 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000494 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000495 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000496 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000497 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000498
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000499 // Ensure that future entries with higher alignment get inserted before
500 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000501 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000502 if (InsPoint[a] == InsAt)
503 InsPoint[a] = CPEMI;
504
Evan Cheng8b7700f2007-02-09 20:54:44 +0000505 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000506 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000507 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000508 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
509 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000510 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000511 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000512}
513
Tim Northovera603c402015-05-31 19:22:07 +0000514/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
515/// instructions can be made more efficient if the jump table immediately
516/// follows the instruction, it's best to place them immediately next to their
517/// jumps to begin with. In almost all cases they'll never be moved from that
518/// position.
519void ARMConstantIslands::doInitialJumpTablePlacement(
520 std::vector<MachineInstr *> &CPEMIs) {
521 unsigned i = CPEntries.size();
522 auto MJTI = MF->getJumpTableInfo();
523 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
524
525 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
526 for (MachineBasicBlock &MBB : *MF) {
527 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000528 if (MI == MBB.end())
529 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000530
531 unsigned JTOpcode;
532 switch (MI->getOpcode()) {
533 default:
534 continue;
535 case ARM::BR_JTadd:
536 case ARM::BR_JTr:
537 case ARM::tBR_JTr:
538 case ARM::BR_JTm:
539 JTOpcode = ARM::JUMPTABLE_ADDRS;
540 break;
541 case ARM::t2BR_JT:
542 JTOpcode = ARM::JUMPTABLE_INSTS;
543 break;
544 case ARM::t2TBB_JT:
545 JTOpcode = ARM::JUMPTABLE_TBB;
546 break;
547 case ARM::t2TBH_JT:
548 JTOpcode = ARM::JUMPTABLE_TBH;
549 break;
550 }
551
552 unsigned NumOps = MI->getDesc().getNumOperands();
553 MachineOperand JTOp =
554 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
555 unsigned JTI = JTOp.getIndex();
556 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
557 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
558 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
559 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
560 DebugLoc(), TII->get(JTOpcode))
561 .addImm(i++)
562 .addJumpTableIndex(JTI)
563 .addImm(Size);
564 CPEMIs.push_back(CPEMI);
565 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
566 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
567 if (!LastCorrectlyNumberedBB)
568 LastCorrectlyNumberedBB = &MBB;
569 }
570
571 // If we did anything then we need to renumber the subsequent blocks.
572 if (LastCorrectlyNumberedBB)
573 MF->RenumberBlocks(LastCorrectlyNumberedBB);
574}
575
Dale Johannesene18b13b2007-02-23 05:02:36 +0000576/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000577/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000578bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000579 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000580 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000581 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000582 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000583 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000584
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000585 MachineBasicBlock *NextBB = &*std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000586 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
587 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000588
Tim Northoverab85dcc2014-11-13 17:58:51 +0000589 // Try to analyze the end of the block. A potential fallthrough may already
590 // have an unconditional branch for whatever reason.
591 MachineBasicBlock *TBB, *FBB;
592 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000593 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000594 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000595}
596
Evan Cheng8b7700f2007-02-09 20:54:44 +0000597/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
598/// look up the corresponding CPEntry.
599ARMConstantIslands::CPEntry
600*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
601 const MachineInstr *CPEMI) {
602 std::vector<CPEntry> &CPEs = CPEntries[CPI];
603 // Number of entries per constpool index should be small, just do a
604 // linear search.
605 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
606 if (CPEs[i].CPEMI == CPEMI)
607 return &CPEs[i];
608 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000609 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000610}
611
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000612/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000613/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000614unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000615 switch (CPEMI->getOpcode()) {
616 case ARM::CONSTPOOL_ENTRY:
617 break;
618 case ARM::JUMPTABLE_TBB:
619 return 0;
620 case ARM::JUMPTABLE_TBH:
621 case ARM::JUMPTABLE_INSTS:
622 return 1;
623 case ARM::JUMPTABLE_ADDRS:
624 return 2;
625 default:
626 llvm_unreachable("unknown constpool entry kind");
627 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000628
Tim Northovera603c402015-05-31 19:22:07 +0000629 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000630 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
631 unsigned Align = MCP->getConstants()[CPI].getAlignment();
632 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
633 return Log2_32(Align);
634}
635
Jim Grosbach190e7b62012-03-23 23:07:03 +0000636/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000637/// information about the sizes of each block and the locations of all
638/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000639void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000640 for (MachineBasicBlock &MBB : *MF) {
641 for (MachineInstr &I : MBB)
642 if (I.isBranch() && I.getOpcode() == ARM::t2BR_JT)
643 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000644 }
645}
646
Jim Grosbach190e7b62012-03-23 23:07:03 +0000647/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000648/// information about the sizes of each block, the location of all the water,
649/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000650void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000651initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000652
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000653 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000654
655 // The known bits of the entry block offset are determined by the function
656 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000657 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000658
659 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000660 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000661
Bill Wendling18581a42010-12-21 01:54:40 +0000662 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000663 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000664 // If this block doesn't fall through into the next MBB, then this is
665 // 'water' that a constant pool island could be placed.
666 if (!BBHasFallthrough(&MBB))
667 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000668
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000669 for (MachineInstr &I : MBB) {
670 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000671 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000672
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000673 unsigned Opc = I.getOpcode();
674 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000675 bool isCond = false;
676 unsigned Bits = 0;
677 unsigned Scale = 1;
678 int UOpc = Opc;
679 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000680 default:
681 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000682 case ARM::t2BR_JT:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000683 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000684 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000685 case ARM::Bcc:
686 isCond = true;
687 UOpc = ARM::B;
688 // Fallthrough
689 case ARM::B:
690 Bits = 24;
691 Scale = 4;
692 break;
693 case ARM::tBcc:
694 isCond = true;
695 UOpc = ARM::tB;
696 Bits = 8;
697 Scale = 2;
698 break;
699 case ARM::tB:
700 Bits = 11;
701 Scale = 2;
702 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000703 case ARM::t2Bcc:
704 isCond = true;
705 UOpc = ARM::t2B;
706 Bits = 20;
707 Scale = 2;
708 break;
709 case ARM::t2B:
710 Bits = 24;
711 Scale = 2;
712 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000713 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000714
715 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000716 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000717 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000718 }
719
Evan Cheng7fa69642007-01-30 01:18:38 +0000720 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000721 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000722
Tim Northovera603c402015-05-31 19:22:07 +0000723 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
724 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
725 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000726 continue;
727
Evan Cheng10043e22007-01-19 07:51:42 +0000728 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000729 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
730 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000731 // We found one. The addressing mode tells us the max displacement
732 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000733
Evan Cheng10043e22007-01-19 07:51:42 +0000734 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000735 unsigned Bits = 0;
736 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000737 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000738 bool IsSoImm = false;
739
740 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000741 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000742 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000743
744 // Taking the address of a CP entry.
745 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000746 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000747 // This takes a SoImm, which is 8 bit immediate rotated. We'll
748 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000749 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000750 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000751 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000752 Scale = 4;
753 NegOk = true;
754 IsSoImm = true;
755 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000756 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000757 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000758 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000759 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000760 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000761 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000762 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000763 Bits = 8;
764 Scale = 4;
765 break;
766
David Majnemer452f1f92013-06-04 17:46:15 +0000767 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000768 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000769 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000770 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000771 Bits = 12; // +-offset_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
775 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000776 Bits = 8;
777 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000778 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000779
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000780 case ARM::VLDRD:
781 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000782 Bits = 8;
783 Scale = 4; // +-(offset_8*4)
784 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000785 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000786 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000787
Evan Cheng10043e22007-01-19 07:51:42 +0000788 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000789 unsigned CPI = I.getOperand(op).getIndex();
790 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000791 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
792 CPI = JumpTableEntryIndices[CPI];
793 }
794
Evan Cheng8b7700f2007-02-09 20:54:44 +0000795 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000796 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000797 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000798
799 // Increment corresponding CPEntry reference count.
800 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
801 assert(CPE && "Cannot find a corresponding CPEntry!");
802 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000803
Evan Cheng10043e22007-01-19 07:51:42 +0000804 // Instructions can only use one CP entry, don't bother scanning the
805 // rest of the operands.
806 break;
807 }
808 }
Evan Cheng10043e22007-01-19 07:51:42 +0000809 }
810}
811
Jim Grosbach190e7b62012-03-23 23:07:03 +0000812/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000813/// from the start of the function. This offset changes as stuff is moved
814/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000815unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000816 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000817
Evan Cheng10043e22007-01-19 07:51:42 +0000818 // The offset is composed of two things: the sum of the sizes of all MBB's
819 // before this instruction's block, and the offset from the start of the block
820 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000821 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000822
823 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000824 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000825 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000826 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000827 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000828 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000829}
830
831/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
832/// ID.
833static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
834 const MachineBasicBlock *RHS) {
835 return LHS->getNumber() < RHS->getNumber();
836}
837
Jim Grosbach190e7b62012-03-23 23:07:03 +0000838/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000839/// machine function, it upsets all of the block numbers. Renumber the blocks
840/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000841void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000842 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000843 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000844
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000845 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000846 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000847 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000848
849 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000850 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000851 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000852 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
853 CompareMBBNumbers);
854 WaterList.insert(IP, NewBB);
855}
856
857
858/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000859/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000860/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000861MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000862 MachineBasicBlock *OrigBB = MI->getParent();
863
864 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000865 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000866 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000867 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000868 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000869
Evan Cheng10043e22007-01-19 07:51:42 +0000870 // Splice the instructions starting with MI over to NewBB.
871 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000872
Evan Cheng10043e22007-01-19 07:51:42 +0000873 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000874 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000875 // There doesn't seem to be meaningful DebugInfo available; this doesn't
876 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000877 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000878 if (!isThumb)
879 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
880 else
881 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
882 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000883 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000884
Evan Cheng10043e22007-01-19 07:51:42 +0000885 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000886 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000887
Evan Cheng10043e22007-01-19 07:51:42 +0000888 // OrigBB branches to NewBB.
889 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000890
Evan Cheng10043e22007-01-19 07:51:42 +0000891 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000892 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000893 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000894 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000895
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000896 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000897 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000898 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000899
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000900 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000901 // available water after it (but not if it's already there, which happens
902 // when splitting before a conditional branch that is followed by an
903 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000904 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000905 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
906 CompareMBBNumbers);
907 MachineBasicBlock* WaterBB = *IP;
908 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000909 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000910 else
911 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000912 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000913
Dale Johannesenc17dd572010-07-23 22:50:23 +0000914 // Figure out how large the OrigBB is. As the first half of the original
915 // block, it cannot contain a tablejump. The size includes
916 // the new jump we added. (It should be possible to do this without
917 // recounting everything, but it's very confusing, and this is rarely
918 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000919 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000920
Dale Johannesenc17dd572010-07-23 22:50:23 +0000921 // Figure out how large the NewMBB is. As the second half of the original
922 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000923 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000924
Dale Johannesen01ee5752007-02-25 00:47:03 +0000925 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000926 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000927
928 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000929}
930
Jim Grosbach190e7b62012-03-23 23:07:03 +0000931/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000932/// displacement computation. Update U.KnownAlignment to match its current
933/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000934unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
935 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000936 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
937 unsigned KnownBits = BBI.internalKnownBits();
938
939 // The value read from PC is offset from the actual instruction address.
940 UserOffset += (isThumb ? 4 : 8);
941
942 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
943 // Make sure U.getMaxDisp() returns a constrained range.
944 U.KnownAlignment = (KnownBits >= 2);
945
946 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
947 // purposes of the displacement computation; compensate for that here.
948 // For unknown alignments, getMaxDisp() constrains the range instead.
949 if (isThumb && U.KnownAlignment)
950 UserOffset &= ~3u;
951
952 return UserOffset;
953}
954
Jim Grosbach190e7b62012-03-23 23:07:03 +0000955/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000956/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000957/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000958/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000959/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
960/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000961bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000962 unsigned TrialOffset, unsigned MaxDisp,
963 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000964 if (UserOffset <= TrialOffset) {
965 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000966 if (TrialOffset - UserOffset <= MaxDisp)
967 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000968 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000969 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000970 if (UserOffset - TrialOffset <= MaxDisp)
971 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000972 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000973 }
974 return false;
975}
976
Jim Grosbach190e7b62012-03-23 23:07:03 +0000977/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000978/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000979///
980/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000981bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000982 MachineBasicBlock* Water, CPUser &U,
983 unsigned &Growth) {
984 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
985 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
986 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000987 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000988 if (++NextBlock == MF->end()) {
989 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
990 NextBlockAlignment = 0;
991 } else {
992 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
993 NextBlockAlignment = NextBlock->getAlignment();
994 }
995 unsigned Size = U.CPEMI->getOperand(2).getImm();
996 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +0000997
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000998 // The CPE may be able to hide in the alignment padding before the next
999 // block. It may also cause more padding to be required if it is more aligned
1000 // that the next block.
1001 if (CPEEnd > NextBlockOffset) {
1002 Growth = CPEEnd - NextBlockOffset;
1003 // Compute the padding that would go at the end of the CPE to align the next
1004 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001005 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001006
1007 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001008 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001009 // in blocks between CPE and the user.
1010 if (CPEOffset < UserOffset)
1011 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1012 } else
1013 // CPE fits in existing padding.
1014 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001015
Jim Grosbach190e7b62012-03-23 23:07:03 +00001016 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001017}
1018
Jim Grosbach190e7b62012-03-23 23:07:03 +00001019/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001020/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001021bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001022 MachineInstr *CPEMI, unsigned MaxDisp,
1023 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001024 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001025
Dale Johannesene18b13b2007-02-23 05:02:36 +00001026 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001027 DEBUG({
1028 unsigned Block = MI->getParent()->getNumber();
1029 const BasicBlockInfo &BBI = BBInfo[Block];
1030 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1031 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001032 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001033 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001034 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1035 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1036 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001037 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001038 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001039
Jim Grosbach190e7b62012-03-23 23:07:03 +00001040 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001041}
1042
Evan Chenge4510972009-01-28 00:53:34 +00001043#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001044/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1045/// unconditionally branches to its only successor.
1046static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1047 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1048 return false;
1049
1050 MachineBasicBlock *Succ = *MBB->succ_begin();
1051 MachineBasicBlock *Pred = *MBB->pred_begin();
1052 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001053 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1054 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001055 return PredMI->getOperand(0).getMBB() == Succ;
1056 return false;
1057}
Evan Chenge4510972009-01-28 00:53:34 +00001058#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001059
Jim Grosbach190e7b62012-03-23 23:07:03 +00001060void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001061 unsigned BBNum = BB->getNumber();
1062 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001063 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001064 // Include the alignment of the current block.
1065 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1066 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1067 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001068
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001069 // This is where block i begins. Stop if the offset is already correct,
1070 // and we have updated 2 blocks. This is the maximum number of blocks
1071 // changed before calling this function.
1072 if (i > BBNum + 2 &&
1073 BBInfo[i].Offset == Offset &&
1074 BBInfo[i].KnownBits == KnownBits)
1075 break;
1076
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001077 BBInfo[i].Offset = Offset;
1078 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001079 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001080}
1081
Jim Grosbach190e7b62012-03-23 23:07:03 +00001082/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001083/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001084/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001085/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001086
Jim Grosbach190e7b62012-03-23 23:07:03 +00001087bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1088 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001089 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001090 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1091 assert(CPE && "Unexpected!");
1092 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001093 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001094 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001095 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001096 return true;
1097 }
1098 return false;
1099}
1100
Tim Northovera603c402015-05-31 19:22:07 +00001101unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1102 if (CPEMI->getOperand(1).isCPI())
1103 return CPEMI->getOperand(1).getIndex();
1104
1105 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1106}
1107
Dale Johannesene18b13b2007-02-23 05:02:36 +00001108/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1109/// if not, see if an in-range clone of the CPE is in range, and if so,
1110/// change the data structures so the user references the clone. Returns:
1111/// 0 = no existing entry found
1112/// 1 = entry found, and there were no code insertions or deletions
1113/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001114int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001115{
1116 MachineInstr *UserMI = U.MI;
1117 MachineInstr *CPEMI = U.CPEMI;
1118
1119 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001120 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1121 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001122 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001123 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001124 }
1125
Dale Johannesene18b13b2007-02-23 05:02:36 +00001126 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001127 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001128 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1129 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1130 // We already tried this one
1131 if (CPEs[i].CPEMI == CPEMI)
1132 continue;
1133 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001134 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001135 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001136 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001137 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001138 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001139 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001140 // Point the CPUser node to the replacement
1141 U.CPEMI = CPEs[i].CPEMI;
1142 // Change the CPI in the instruction operand to refer to the clone.
1143 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001144 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001145 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001146 break;
1147 }
1148 // Adjust the refcount of the clone...
1149 CPEs[i].RefCount++;
1150 // ...and the original. If we didn't remove the old entry, none of the
1151 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001152 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001153 }
1154 }
1155 return 0;
1156}
1157
Dale Johannesen440995b2007-02-28 18:41:23 +00001158/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1159/// the specific unconditional branch instruction.
1160static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001161 switch (Opc) {
1162 case ARM::tB:
1163 return ((1<<10)-1)*2;
1164 case ARM::t2B:
1165 return ((1<<23)-1)*2;
1166 default:
1167 break;
1168 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001169
David Goodwin27303cd2009-06-30 18:04:13 +00001170 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001171}
1172
Jim Grosbach190e7b62012-03-23 23:07:03 +00001173/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001174/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001175/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001176/// is set to the WaterList entry. For Thumb, prefer water that will not
1177/// introduce padding to water that will. To ensure that this pass
1178/// terminates, the CPE location for a particular CPUser is only allowed to
1179/// move to a lower address, so search backward from the end of the list and
1180/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001181bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001182 water_iterator &WaterIter,
1183 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001184 if (WaterList.empty())
1185 return false;
1186
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001187 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001188 // The nearest water without splitting the UserBB is right after it.
1189 // If the distance is still large (we have a big BB), then we need to split it
1190 // if we don't converge after certain iterations. This helps the following
1191 // situation to converge:
1192 // BB0:
1193 // Big BB
1194 // BB1:
1195 // Constant Pool
1196 // When a CP access is out of range, BB0 may be used as water. However,
1197 // inserting islands between BB0 and BB1 makes other accesses out of range.
1198 MachineBasicBlock *UserBB = U.MI->getParent();
1199 unsigned MinNoSplitDisp =
1200 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1201 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1202 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001203 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001204 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001205 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001206 // Check if water is in range and is either at a lower address than the
1207 // current "high water mark" or a new water block that was created since
1208 // the previous iteration by inserting an unconditional branch. In the
1209 // latter case, we want to allow resetting the high water mark back to
1210 // this new water since we haven't seen it before. Inserting branches
1211 // should be relatively uncommon and when it does happen, we want to be
1212 // sure to take advantage of it for all the CPEs near that block, so that
1213 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001214 // When CloserWater is true, we try to find the lowest address after (or
1215 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001216 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001217 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001218 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001219 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1220 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001221 // This is the least amount of required padding seen so far.
1222 BestGrowth = Growth;
1223 WaterIter = IP;
1224 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1225 << " Growth=" << Growth << '\n');
1226
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001227 if (CloserWater && WaterBB == U.MI->getParent())
1228 return true;
1229 // Keep looking unless it is perfect and we're not looking for the lowest
1230 // possible address.
1231 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001232 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001233 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001234 if (IP == B)
1235 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001236 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001237 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001238}
1239
Jim Grosbach190e7b62012-03-23 23:07:03 +00001240/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001241/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1242/// block is used if in range, and the conditional branch munged so control
1243/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001244/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001245/// block following which the new island can be inserted (the WaterList
1246/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001247void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001248 unsigned UserOffset,
1249 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001250 CPUser &U = CPUsers[CPUserIndex];
1251 MachineInstr *UserMI = U.MI;
1252 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001253 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001254 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001255 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001256
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001257 // If the block does not end in an unconditional branch already, and if the
1258 // end of the block is within range, make new water there. (The addition
1259 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001260 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001261 if (BBHasFallthrough(UserMBB)) {
1262 // Size of branch to insert.
1263 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001264 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001265 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001266
Jim Grosbach190e7b62012-03-23 23:07:03 +00001267 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001268 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1269 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001270 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001271 // Add an unconditional branch from UserMBB to fallthrough block. Record
1272 // it for branch lengthening; this new branch will not get out of range,
1273 // but if the preceding conditional branch is out of range, the targets
1274 // will be exchanged, and the altered branch may be out of range, so the
1275 // machinery has to know about it.
1276 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1277 if (!isThumb)
1278 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1279 else
1280 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1281 .addImm(ARMCC::AL).addReg(0);
1282 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1283 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1284 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001285 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001286 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001287 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001288 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001289 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001290
1291 // What a big block. Find a place within the block to split it. This is a
1292 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1293 // entries are 4 bytes: if instruction I references island CPE, and
1294 // instruction I+1 references CPE', it will not work well to put CPE as far
1295 // forward as possible, since then CPE' cannot immediately follow it (that
1296 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1297 // need to create a new island. So, we make a first guess, then walk through
1298 // the instructions between the one currently being looked at and the
1299 // possible insertion point, and make sure any other instructions that
1300 // reference CPEs will be able to use the same island area; if not, we back
1301 // up the insertion point.
1302
1303 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001304 // point where we can add a 4-byte branch instruction, and then align to
1305 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001306 unsigned LogAlign = MF->getAlignment();
1307 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1308 unsigned KnownBits = UserBBI.internalKnownBits();
1309 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001310 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001311 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1312 BaseInsertOffset));
1313
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001314 // The 4 in the following is for the unconditional branch we'll be inserting
1315 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001316 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001317 BaseInsertOffset -= 4;
1318
1319 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1320 << " la=" << LogAlign
1321 << " kb=" << KnownBits
1322 << " up=" << UPad << '\n');
1323
1324 // This could point off the end of the block if we've already got constant
1325 // pool entries following this block; only the last one is in the water list.
1326 // Back past any possible branches (allow for a conditional and a maximally
1327 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001328 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001329 // Ensure BaseInsertOffset is larger than the offset of the instruction
1330 // following UserMI so that the loop which searches for the split point
1331 // iterates at least once.
1332 BaseInsertOffset =
1333 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001334 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001335 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1336 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001337 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001338 CPEMI->getOperand(2).getImm();
1339 MachineBasicBlock::iterator MI = UserMI;
1340 ++MI;
1341 unsigned CPUIndex = CPUserIndex+1;
1342 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001343 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001344 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001345 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001346 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001347 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001348 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001349 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001350 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001351 // Shift intertion point by one unit of alignment so it is within reach.
1352 BaseInsertOffset -= 1u << LogAlign;
1353 EndInsertOffset -= 1u << LogAlign;
1354 }
1355 // This is overly conservative, as we don't account for CPEMIs being
1356 // reused within the block, but it doesn't matter much. Also assume CPEs
1357 // are added in order with alignment padding. We may eventually be able
1358 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001359 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001360 CPUIndex++;
1361 }
1362
1363 // Remember the last IT instruction.
1364 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001365 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001366 }
1367
1368 --MI;
1369
1370 // Avoid splitting an IT block.
1371 if (LastIT) {
1372 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001373 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001374 if (CC != ARMCC::AL)
1375 MI = LastIT;
1376 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001377
1378 // We really must not split an IT block.
1379 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001380 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001381
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001382 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001383}
1384
Jim Grosbach190e7b62012-03-23 23:07:03 +00001385/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001386/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001387/// place in-range. Return true if we changed any addresses (thus must run
1388/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001389bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1390 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001391 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001392 MachineInstr *UserMI = U.MI;
1393 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001394 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001395 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001396 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001397 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001398
Dale Johannesene18b13b2007-02-23 05:02:36 +00001399 // See if the current entry is within range, or there is a clone of it
1400 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001401 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001402 if (result==1) return false;
1403 else if (result==2) return true;
1404
1405 // No existing clone of this CPE is within range.
1406 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001407 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001408
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001409 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001410 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001411 MachineBasicBlock *NewMBB;
1412 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001413 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001414 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001415 MachineBasicBlock *WaterBB = *IP;
1416
1417 // If the original WaterList entry was "new water" on this iteration,
1418 // propagate that to the new island. This is just keeping NewWaterList
1419 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001420 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001421 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001422
Bob Wilson2f9be502009-10-15 20:49:47 +00001423 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001424 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001425 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001426 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001427 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001428 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001429
Jim Grosbach190e7b62012-03-23 23:07:03 +00001430 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001431 // called while handling branches so that the water will be seen on the
1432 // next iteration for constant pools, but in this context, we don't want
1433 // it. Check for this so it will be removed from the WaterList.
1434 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001435 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001436 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1437 if (IP != WaterList.end())
1438 NewWaterList.erase(WaterBB);
1439
1440 // We are adding new water. Update NewWaterList.
1441 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001442 }
1443
Bob Wilson2f9be502009-10-15 20:49:47 +00001444 // Remove the original WaterList entry; we want subsequent insertions in
1445 // this vicinity to go after the one we're about to insert. This
1446 // considerably reduces the number of times we have to move the same CPE
1447 // more than once and is also important to ensure the algorithm terminates.
1448 if (IP != WaterList.end())
1449 WaterList.erase(IP);
1450
Dale Johannesene18b13b2007-02-23 05:02:36 +00001451 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001452 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001453
1454 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001455 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001456
Dale Johannesene18b13b2007-02-23 05:02:36 +00001457 // Now that we have an island to add the CPE to, clone the original CPE and
1458 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001459 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001460 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1461 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001462 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001463 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001464
Tim Northovera603c402015-05-31 19:22:07 +00001465 // Decrement the old entry, and remove it if refcount becomes 0.
1466 decrementCPEReferenceCount(CPI, CPEMI);
1467
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001468 // Mark the basic block as aligned as required by the const-pool entry.
1469 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001470
Evan Cheng10043e22007-01-19 07:51:42 +00001471 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001472 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001473 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001474
Evan Cheng10043e22007-01-19 07:51:42 +00001475 // Finally, change the CPI in the instruction operand to be ID.
1476 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001477 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001478 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001479 break;
1480 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001481
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001482 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001483 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001484
Evan Cheng10043e22007-01-19 07:51:42 +00001485 return true;
1486}
1487
Jim Grosbach190e7b62012-03-23 23:07:03 +00001488/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001489/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001490void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001491 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001492 unsigned Size = CPEMI->getOperand(2).getImm();
1493 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001494 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001495 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001496 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001497 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001498
Evan Chengab28b9a2013-02-21 18:37:54 +00001499 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001500 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001501 } else
1502 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001503 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001504
Jim Grosbach190e7b62012-03-23 23:07:03 +00001505 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001506 // An island has only one predecessor BB and one successor BB. Check if
1507 // this BB's predecessor jumps directly to this BB's successor. This
1508 // shouldn't happen currently.
1509 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1510 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001511}
1512
Jim Grosbach190e7b62012-03-23 23:07:03 +00001513/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001514/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001515bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001516 unsigned MadeChange = false;
1517 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1518 std::vector<CPEntry> &CPEs = CPEntries[i];
1519 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1520 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001521 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001522 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001523 MadeChange = true;
1524 }
1525 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001526 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001527 return MadeChange;
1528}
1529
Jim Grosbach190e7b62012-03-23 23:07:03 +00001530/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001531/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001532bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001533 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001534 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001535 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001536 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001537
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001538 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001539 << " from BB#" << MI->getParent()->getNumber()
1540 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001541 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001542 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001543
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001544 if (BrOffset <= DestOffset) {
1545 // Branch before the Dest.
1546 if (DestOffset-BrOffset <= MaxDisp)
1547 return true;
1548 } else {
1549 if (BrOffset-DestOffset <= MaxDisp)
1550 return true;
1551 }
1552 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001553}
1554
Jim Grosbach190e7b62012-03-23 23:07:03 +00001555/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001556/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001557bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001558 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001559 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001560
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001561 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001562 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001563 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001564
Evan Cheng7fa69642007-01-30 01:18:38 +00001565 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001566 return fixupUnconditionalBr(Br);
1567 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001568}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001569
Jim Grosbach190e7b62012-03-23 23:07:03 +00001570/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001571/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001572/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001573/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001574bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001575ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001576 MachineInstr *MI = Br.MI;
1577 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001578 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001579 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001580
1581 // Use BL to implement far jump.
1582 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001583 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001584 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001585 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001586 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001587 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001588
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001589 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001590
Evan Cheng7fa69642007-01-30 01:18:38 +00001591 return true;
1592}
1593
Jim Grosbach190e7b62012-03-23 23:07:03 +00001594/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001595/// far away to fit in its displacement field. It is converted to an inverse
1596/// conditional branch + an unconditional branch to the destination.
1597bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001598ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001599 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001600 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001601
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001602 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001603 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001604 // blt L1
1605 // =>
1606 // bge L2
1607 // b L1
1608 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001609 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001610 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001611 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001612
1613 // If the branch is at the end of its MBB and that has a fall-through block,
1614 // direct the updated conditional branch to the fall-through block. Otherwise,
1615 // split the MBB before the next instruction.
1616 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001617 MachineInstr *BMI = &MBB->back();
1618 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001619
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001620 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001621 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001622 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001623 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001624 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001625 // condition and swap destinations:
1626 // beq L1
1627 // b L2
1628 // =>
1629 // bne L2
1630 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001631 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001632 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001633 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001634 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001635 BMI->getOperand(0).setMBB(DestBB);
1636 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001637 MI->getOperand(1).setImm(CC);
1638 return true;
1639 }
1640 }
1641 }
1642
1643 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001644 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001645 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001646 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001647 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001648 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001649 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001650 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001651 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001652 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001653
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001654 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001655 << " also invert condition and change dest. to BB#"
1656 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001657
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001658 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001659 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001660 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001661 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001662 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001663 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001664 if (isThumb)
1665 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1666 .addImm(ARMCC::AL).addReg(0);
1667 else
1668 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001669 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001670 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001671 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001672
1673 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001674 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001675 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001676 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001677 return true;
1678}
Evan Cheng7fa69642007-01-30 01:18:38 +00001679
Jim Grosbach190e7b62012-03-23 23:07:03 +00001680/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001681/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1682/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001683bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001684 bool MadeChange = false;
1685 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1686 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001687 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001688 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001689 MI->getOperand(2).getReg() == ARM::PC &&
1690 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001691 // Create the new insn and copy the predicate from the old.
1692 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1693 .addOperand(MI->getOperand(0))
1694 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001695 MI->eraseFromParent();
1696 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001697 }
1698 }
1699 return MadeChange;
1700}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001701
Jim Grosbach190e7b62012-03-23 23:07:03 +00001702// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001703// below may shrink MI.
1704bool
1705ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1706 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001707 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001708 case ARM::t2LEApcrel:
1709 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001710 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001711 case ARM::t2B:
1712 case ARM::t2Bcc:
1713 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001714 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001715 case ARM::t2BR_JT:
1716 return true;
1717 }
1718 return false;
1719}
1720
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();
1960 DeadSize += 4;
1961 } 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
Tim Northovera603c402015-05-31 19:22:07 +00002027 MachineBasicBlock *MBB = MI->getParent();
2028 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2029 continue;
2030 unsigned IdxReg = MI->getOperand(1).getReg();
2031 bool IdxRegKill = MI->getOperand(1).isKill();
2032
2033 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2034 unsigned DeadSize = 0;
2035 bool CanDeleteLEA = false;
2036 bool BaseRegKill = false;
2037 bool PreservedBaseReg =
2038 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2039
2040 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2041 continue;
2042
2043 DEBUG(dbgs() << "Shrink JT: " << *MI);
2044 MachineInstr *CPEMI = User.CPEMI;
2045 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2046 MachineBasicBlock::iterator MI_JT = MI;
2047 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002048 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002049 .addReg(User.MI->getOperand(0).getReg(),
2050 getKillRegState(BaseRegKill))
2051 .addReg(IdxReg, getKillRegState(IdxRegKill))
2052 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2053 .addImm(CPEMI->getOperand(0).getImm());
2054 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002055
Tim Northovera603c402015-05-31 19:22:07 +00002056 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2057 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002058
Tim Northovera603c402015-05-31 19:22:07 +00002059 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2060 NewJTMI->getOperand(0).setReg(ARM::PC);
2061 NewJTMI->getOperand(0).setIsKill(false);
2062
2063 if (CanDeleteLEA) {
2064 User.MI->eraseFromParent();
2065 DeadSize += 4;
2066
2067 // The LEA was eliminated, the TBB instruction becomes the only new user
2068 // of the jump table.
2069 User.MI = NewJTMI;
2070 User.MaxDisp = 4;
2071 User.NegOk = false;
2072 User.IsSoImm = false;
2073 User.KnownAlignment = false;
2074 } else {
2075 // The LEA couldn't be eliminated, so we must add another CPUser to
2076 // record the TBB or TBH use.
2077 int CPEntryIdx = JumpTableEntryIndices[JTI];
2078 auto &CPEs = CPEntries[CPEntryIdx];
2079 auto Entry = std::find_if(CPEs.begin(), CPEs.end(), [&](CPEntry &E) {
2080 return E.CPEMI == User.CPEMI;
2081 });
2082 ++Entry->RefCount;
2083 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2084 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002085 }
Tim Northovera603c402015-05-31 19:22:07 +00002086
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002087 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2088 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002089 MI->eraseFromParent();
2090
2091 int Delta = OrigSize - NewSize + DeadSize;
2092 BBInfo[MBB->getNumber()].Size -= Delta;
2093 adjustBBOffsetsAfter(MBB);
2094
2095 ++NumTBs;
2096 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002097 }
2098
2099 return MadeChange;
2100}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002101
Jim Grosbach190e7b62012-03-23 23:07:03 +00002102/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002103/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002104bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002105 bool MadeChange = false;
2106
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002107 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002108 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002109
Jim Grosbach5d577142009-11-12 17:25:07 +00002110 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2111 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2112 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002113 const MCInstrDesc &MCID = MI->getDesc();
2114 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002115 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002116 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2117 unsigned JTI = JTOP.getIndex();
2118 assert(JTI < JT.size());
2119
2120 // We prefer if target blocks for the jump table come after the jump
2121 // instruction so we can use TB[BH]. Loop through the target blocks
2122 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002123 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002124 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2125 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2126 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002127 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002128
Jim Grosbach9785e592009-11-16 18:58:52 +00002129 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002130 // The destination precedes the switch. Try to move the block forward
2131 // so we have a positive offset.
2132 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002133 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002134 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002135 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002136 MadeChange = true;
2137 }
2138 }
2139 }
2140
2141 return MadeChange;
2142}
2143
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002144MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002145adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002146 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002147 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002148 // table that branches back to the actual target. This is a very simple
2149 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002150 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002151 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002152 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002153 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002154 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002155
Jim Grosbach47d5e332009-11-16 17:10:56 +00002156 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002157 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002158
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002159 // If the block ends in an unconditional branch, move it. The prior block
2160 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002161 // 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 +00002162 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002163 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002164 BB->moveAfter(JTBB);
2165 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002166 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002167 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002168 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002169 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002170 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002171 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002172
2173 // Create a new MBB for the code after the jump BB.
2174 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002175 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002176 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002177 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002178
2179 // Add an unconditional branch from NewBB to BB.
2180 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2181 // correspond directly to anything in the source.
2182 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002183 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2184 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002185
Jim Grosbach43d21082009-11-14 20:10:18 +00002186 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002187 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002188
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002189 // Update the CFG.
2190 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002191 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002192
Jim Grosbach5d577142009-11-12 17:25:07 +00002193 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002194 return NewBB;
2195}