blob: fd679f0f6b0d469ef226e2d8046694f1b8f8f3c9 [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(
Matthias Braun1eb47362016-08-25 01:27:13 +0000200 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000201 }
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();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000238 bool optimizeThumb2Instructions();
239 bool optimizeThumb2Branches();
240 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000241 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
242 unsigned &DeadSize, bool &CanDeleteLEA,
243 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000244 bool optimizeThumb2JumpTables();
245 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000246 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000247
Jim Grosbach190e7b62012-03-23 23:07:03 +0000248 unsigned getOffsetOf(MachineInstr *MI) const;
249 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000250 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000251 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000252
Jim Grosbach190e7b62012-03-23 23:07:03 +0000253 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000254 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000255 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000256 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000257 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000258 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000259 }
Evan Cheng10043e22007-01-19 07:51:42 +0000260 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000261 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000262}
Evan Cheng10043e22007-01-19 07:51:42 +0000263
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000264/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000265void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000266#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000267 assert(std::is_sorted(MF->begin(), MF->end(),
268 [this](const MachineBasicBlock &LHS,
269 const MachineBasicBlock &RHS) {
270 return BBInfo[LHS.getNumber()].postOffset() <
271 BBInfo[RHS.getNumber()].postOffset();
272 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000273 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000274 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
275 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000276 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000277 // Verify offset using the real max displacement without the safety
278 // adjustment.
279 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000280 /* DoDump = */ true)) {
281 DEBUG(dbgs() << "OK\n");
282 continue;
283 }
284 DEBUG(dbgs() << "Out of range.\n");
285 dumpBBs();
286 DEBUG(MF->dump());
287 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000288 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000289#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000290}
291
292/// print block size and offset information - debugging
293void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000294 DEBUG({
295 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
296 const BasicBlockInfo &BBI = BBInfo[J];
297 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
298 << " kb=" << unsigned(BBI.KnownBits)
299 << " ua=" << unsigned(BBI.Unalign)
300 << " pa=" << unsigned(BBI.PostAlign)
301 << format(" size=%#x\n", BBInfo[J].Size);
302 }
303 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000304}
305
Evan Cheng22c7cf52007-01-25 03:12:46 +0000306/// createARMConstantIslandPass - returns an instance of the constpool
307/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000308FunctionPass *llvm::createARMConstantIslandPass() {
309 return new ARMConstantIslands();
310}
311
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000312bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
313 MF = &mf;
314 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000315
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000316 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000317 << MCP->getConstants().size() << " CP entries, aligned to "
318 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000319
Eric Christopher1b21f002015-01-29 00:19:33 +0000320 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
321 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000322 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000323
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000324 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000325 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000326 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000327
328 HasFarJump = false;
329
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000330 // This pass invalidates liveness information when it splits basic blocks.
331 MF->getRegInfo().invalidateLiveness();
332
Evan Cheng10043e22007-01-19 07:51:42 +0000333 // Renumber all of the machine basic blocks in the function, guaranteeing that
334 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000335 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000336
Jim Grosbach5d577142009-11-12 17:25:07 +0000337 // Try to reorder and otherwise adjust the block layout to make good use
338 // of the TB[BH] instructions.
339 bool MadeChange = false;
340 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000341 scanFunctionJumpTables();
342 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000343 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000344 T2JumpTables.clear();
345 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000346 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000347 }
348
Evan Cheng10043e22007-01-19 07:51:42 +0000349 // Perform the initial placement of the constant pool entries. To start with,
350 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000351 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000352 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000353 doInitialConstPlacement(CPEMIs);
354
355 if (MF->getJumpTableInfo())
356 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000357
Evan Cheng10043e22007-01-19 07:51:42 +0000358 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000359 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000360
Evan Cheng10043e22007-01-19 07:51:42 +0000361 // Do the initial scan of the function, building up information about the
362 // sizes of each block, the location of all the water, and finding all of the
363 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000364 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000365 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000366 DEBUG(dumpBBs());
367
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000368 // Functions with jump tables need an alignment of 4 because they use the ADR
369 // instruction, which aligns the PC to 4 bytes before adding an offset.
370 if (!T2JumpTables.empty())
371 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000372
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000373 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000374 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000375
Evan Cheng7fa69642007-01-30 01:18:38 +0000376 // Iteratively place constant pool entries and fix up branches until there
377 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000378 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000379 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000380 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000381 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000382 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000383 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000384 // If it doesn't end in 10, the input may have huge BB or many CPEs.
385 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000386 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
387 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000388 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000389 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000390
Bob Wilson2f9be502009-10-15 20:49:47 +0000391 // Clear NewWaterList now. If we split a block for branches, it should
392 // appear as "new water" for the next iteration of constant pool placement.
393 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000394
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000395 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000396 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000397 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000398 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000399 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000400 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000401 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000402
403 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000404 break;
405 MadeChange = true;
406 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000407
Bradley Smitha1189102016-01-15 10:26:17 +0000408 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000409 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000410 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000411
Bradley Smitha1189102016-01-15 10:26:17 +0000412 // Shrink 32-bit branch instructions.
413 if (isThumb && STI->hasV8MBaselineOps())
414 MadeChange |= optimizeThumb2Branches();
415
416 // Optimize jump tables using TBB / TBH.
417 if (isThumb2)
418 MadeChange |= optimizeThumb2JumpTables();
419
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000420 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000421 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000422
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000423 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
424 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000425 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000426 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000427
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000428 // Save the mapping between original and cloned constpool entries.
429 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
430 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
431 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000432 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
433 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000434 }
435 }
436
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000437 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000438
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000439 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000440 WaterList.clear();
441 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000442 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000443 JumpTableEntryIndices.clear();
444 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000445 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000446 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000447 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000448
449 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000450}
451
Tim Northovera603c402015-05-31 19:22:07 +0000452/// \brief Perform the initial placement of the regular constant pool entries.
453/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000454void
Tim Northovera603c402015-05-31 19:22:07 +0000455ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000456 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000457 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
458 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000459
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000460 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000461 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000462
463 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000464 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000465
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000466 // The function needs to be as aligned as the basic blocks. The linker may
467 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000468 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000469
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000470 // Order the entries in BB by descending alignment. That ensures correct
471 // alignment of all entries as long as BB is sufficiently aligned. Keep
472 // track of the insertion point for each alignment. We are going to bucket
473 // sort the entries as they are created.
474 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000475
Evan Cheng10043e22007-01-19 07:51:42 +0000476 // Add all of the constants from the constant pool to the end block, use an
477 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000478 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000479
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000480 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000481 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000482 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000483 assert(Size >= 4 && "Too small constant pool entry");
484 unsigned Align = CPs[i].getAlignment();
485 assert(isPowerOf2_32(Align) && "Invalid alignment");
486 // Verify that all constant pool entries are a multiple of their alignment.
487 // If not, we would have to pad them out so that instructions stay aligned.
488 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
489
490 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
491 unsigned LogAlign = Log2_32(Align);
492 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000493 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000494 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000495 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000496 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000497
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000498 // Ensure that future entries with higher alignment get inserted before
499 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000500 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000501 if (InsPoint[a] == InsAt)
502 InsPoint[a] = CPEMI;
503
Evan Cheng8b7700f2007-02-09 20:54:44 +0000504 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000505 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000506 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000507 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
508 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000509 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000510 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000511}
512
Tim Northovera603c402015-05-31 19:22:07 +0000513/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
514/// instructions can be made more efficient if the jump table immediately
515/// follows the instruction, it's best to place them immediately next to their
516/// jumps to begin with. In almost all cases they'll never be moved from that
517/// position.
518void ARMConstantIslands::doInitialJumpTablePlacement(
519 std::vector<MachineInstr *> &CPEMIs) {
520 unsigned i = CPEntries.size();
521 auto MJTI = MF->getJumpTableInfo();
522 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
523
524 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
525 for (MachineBasicBlock &MBB : *MF) {
526 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000527 if (MI == MBB.end())
528 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000529
530 unsigned JTOpcode;
531 switch (MI->getOpcode()) {
532 default:
533 continue;
534 case ARM::BR_JTadd:
535 case ARM::BR_JTr:
536 case ARM::tBR_JTr:
537 case ARM::BR_JTm:
538 JTOpcode = ARM::JUMPTABLE_ADDRS;
539 break;
540 case ARM::t2BR_JT:
541 JTOpcode = ARM::JUMPTABLE_INSTS;
542 break;
543 case ARM::t2TBB_JT:
544 JTOpcode = ARM::JUMPTABLE_TBB;
545 break;
546 case ARM::t2TBH_JT:
547 JTOpcode = ARM::JUMPTABLE_TBH;
548 break;
549 }
550
551 unsigned NumOps = MI->getDesc().getNumOperands();
552 MachineOperand JTOp =
553 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
554 unsigned JTI = JTOp.getIndex();
555 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
556 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
557 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
558 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
559 DebugLoc(), TII->get(JTOpcode))
560 .addImm(i++)
561 .addJumpTableIndex(JTI)
562 .addImm(Size);
563 CPEMIs.push_back(CPEMI);
564 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
565 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
566 if (!LastCorrectlyNumberedBB)
567 LastCorrectlyNumberedBB = &MBB;
568 }
569
570 // If we did anything then we need to renumber the subsequent blocks.
571 if (LastCorrectlyNumberedBB)
572 MF->RenumberBlocks(LastCorrectlyNumberedBB);
573}
574
Dale Johannesene18b13b2007-02-23 05:02:36 +0000575/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000576/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000577bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000578 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000579 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000580 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000581 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000582 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000583
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000584 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000585 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000586 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000587
Tim Northoverab85dcc2014-11-13 17:58:51 +0000588 // Try to analyze the end of the block. A potential fallthrough may already
589 // have an unconditional branch for whatever reason.
590 MachineBasicBlock *TBB, *FBB;
591 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000592 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000593 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000594}
595
Evan Cheng8b7700f2007-02-09 20:54:44 +0000596/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
597/// look up the corresponding CPEntry.
598ARMConstantIslands::CPEntry
599*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
600 const MachineInstr *CPEMI) {
601 std::vector<CPEntry> &CPEs = CPEntries[CPI];
602 // Number of entries per constpool index should be small, just do a
603 // linear search.
604 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
605 if (CPEs[i].CPEMI == CPEMI)
606 return &CPEs[i];
607 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000608 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000609}
610
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000611/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000612/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000613unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000614 switch (CPEMI->getOpcode()) {
615 case ARM::CONSTPOOL_ENTRY:
616 break;
617 case ARM::JUMPTABLE_TBB:
618 return 0;
619 case ARM::JUMPTABLE_TBH:
620 case ARM::JUMPTABLE_INSTS:
621 return 1;
622 case ARM::JUMPTABLE_ADDRS:
623 return 2;
624 default:
625 llvm_unreachable("unknown constpool entry kind");
626 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000627
Tim Northovera603c402015-05-31 19:22:07 +0000628 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000629 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
630 unsigned Align = MCP->getConstants()[CPI].getAlignment();
631 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
632 return Log2_32(Align);
633}
634
Jim Grosbach190e7b62012-03-23 23:07:03 +0000635/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000636/// information about the sizes of each block and the locations of all
637/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000638void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000639 for (MachineBasicBlock &MBB : *MF) {
640 for (MachineInstr &I : MBB)
641 if (I.isBranch() && I.getOpcode() == ARM::t2BR_JT)
642 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000643 }
644}
645
Jim Grosbach190e7b62012-03-23 23:07:03 +0000646/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000647/// information about the sizes of each block, the location of all the water,
648/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000649void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000650initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000651
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000652 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000653
654 // The known bits of the entry block offset are determined by the function
655 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000656 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000657
658 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000659 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000660
Bill Wendling18581a42010-12-21 01:54:40 +0000661 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000662 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000663 // If this block doesn't fall through into the next MBB, then this is
664 // 'water' that a constant pool island could be placed.
665 if (!BBHasFallthrough(&MBB))
666 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000667
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000668 for (MachineInstr &I : MBB) {
669 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000670 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000671
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000672 unsigned Opc = I.getOpcode();
673 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000674 bool isCond = false;
675 unsigned Bits = 0;
676 unsigned Scale = 1;
677 int UOpc = Opc;
678 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000679 default:
680 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000681 case ARM::t2BR_JT:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000682 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000683 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000684 case ARM::Bcc:
685 isCond = true;
686 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000687 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000688 case ARM::B:
689 Bits = 24;
690 Scale = 4;
691 break;
692 case ARM::tBcc:
693 isCond = true;
694 UOpc = ARM::tB;
695 Bits = 8;
696 Scale = 2;
697 break;
698 case ARM::tB:
699 Bits = 11;
700 Scale = 2;
701 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000702 case ARM::t2Bcc:
703 isCond = true;
704 UOpc = ARM::t2B;
705 Bits = 20;
706 Scale = 2;
707 break;
708 case ARM::t2B:
709 Bits = 24;
710 Scale = 2;
711 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000712 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000713
714 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000715 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000716 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000717 }
718
Evan Cheng7fa69642007-01-30 01:18:38 +0000719 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000720 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000721
Tim Northovera603c402015-05-31 19:22:07 +0000722 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
723 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
724 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000725 continue;
726
Evan Cheng10043e22007-01-19 07:51:42 +0000727 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000728 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
729 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000730 // We found one. The addressing mode tells us the max displacement
731 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000732
Evan Cheng10043e22007-01-19 07:51:42 +0000733 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000734 unsigned Bits = 0;
735 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000736 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000737 bool IsSoImm = false;
738
739 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000740 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000741 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000742
743 // Taking the address of a CP entry.
744 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000745 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000746 // This takes a SoImm, which is 8 bit immediate rotated. We'll
747 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000748 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000749 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000750 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000751 Scale = 4;
752 NegOk = true;
753 IsSoImm = true;
754 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000755 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000756 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000757 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000758 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000759 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000760 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000761 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000762 Bits = 8;
763 Scale = 4;
764 break;
765
David Majnemer452f1f92013-06-04 17:46:15 +0000766 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000767 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000768 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000769 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000770 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000771 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000772 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000773
774 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000775 Bits = 8;
776 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000777 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000778
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000779 case ARM::VLDRD:
780 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000781 Bits = 8;
782 Scale = 4; // +-(offset_8*4)
783 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000784 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000785 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000786
Evan Cheng10043e22007-01-19 07:51:42 +0000787 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000788 unsigned CPI = I.getOperand(op).getIndex();
789 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000790 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
791 CPI = JumpTableEntryIndices[CPI];
792 }
793
Evan Cheng8b7700f2007-02-09 20:54:44 +0000794 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000795 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000796 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000797
798 // Increment corresponding CPEntry reference count.
799 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
800 assert(CPE && "Cannot find a corresponding CPEntry!");
801 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000802
Evan Cheng10043e22007-01-19 07:51:42 +0000803 // Instructions can only use one CP entry, don't bother scanning the
804 // rest of the operands.
805 break;
806 }
807 }
Evan Cheng10043e22007-01-19 07:51:42 +0000808 }
809}
810
Jim Grosbach190e7b62012-03-23 23:07:03 +0000811/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000812/// from the start of the function. This offset changes as stuff is moved
813/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000814unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000815 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000816
Evan Cheng10043e22007-01-19 07:51:42 +0000817 // The offset is composed of two things: the sum of the sizes of all MBB's
818 // before this instruction's block, and the offset from the start of the block
819 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000820 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000821
822 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000823 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000824 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000825 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000826 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000827 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000828}
829
830/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
831/// ID.
832static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
833 const MachineBasicBlock *RHS) {
834 return LHS->getNumber() < RHS->getNumber();
835}
836
Jim Grosbach190e7b62012-03-23 23:07:03 +0000837/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000838/// machine function, it upsets all of the block numbers. Renumber the blocks
839/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000840void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000841 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000842 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000843
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000844 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000845 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000846 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000847
848 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000849 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000850 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000851 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
852 CompareMBBNumbers);
853 WaterList.insert(IP, NewBB);
854}
855
856
857/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000858/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000859/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000860MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000861 MachineBasicBlock *OrigBB = MI->getParent();
862
863 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000864 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000865 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000866 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000867 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000868
Evan Cheng10043e22007-01-19 07:51:42 +0000869 // Splice the instructions starting with MI over to NewBB.
870 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000871
Evan Cheng10043e22007-01-19 07:51:42 +0000872 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000873 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000874 // There doesn't seem to be meaningful DebugInfo available; this doesn't
875 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000876 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000877 if (!isThumb)
878 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
879 else
880 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
881 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000882 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000883
Evan Cheng10043e22007-01-19 07:51:42 +0000884 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000885 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000886
Evan Cheng10043e22007-01-19 07:51:42 +0000887 // OrigBB branches to NewBB.
888 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000889
Evan Cheng10043e22007-01-19 07:51:42 +0000890 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000891 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000892 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000893 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000894
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000895 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000896 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000897 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000898
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000899 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000900 // available water after it (but not if it's already there, which happens
901 // when splitting before a conditional branch that is followed by an
902 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000903 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000904 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
905 CompareMBBNumbers);
906 MachineBasicBlock* WaterBB = *IP;
907 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000908 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000909 else
910 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000911 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000912
Dale Johannesenc17dd572010-07-23 22:50:23 +0000913 // Figure out how large the OrigBB is. As the first half of the original
914 // block, it cannot contain a tablejump. The size includes
915 // the new jump we added. (It should be possible to do this without
916 // recounting everything, but it's very confusing, and this is rarely
917 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000918 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000919
Dale Johannesenc17dd572010-07-23 22:50:23 +0000920 // Figure out how large the NewMBB is. As the second half of the original
921 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000922 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000923
Dale Johannesen01ee5752007-02-25 00:47:03 +0000924 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000925 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000926
927 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000928}
929
Jim Grosbach190e7b62012-03-23 23:07:03 +0000930/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000931/// displacement computation. Update U.KnownAlignment to match its current
932/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000933unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
934 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000935 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
936 unsigned KnownBits = BBI.internalKnownBits();
937
938 // The value read from PC is offset from the actual instruction address.
939 UserOffset += (isThumb ? 4 : 8);
940
941 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
942 // Make sure U.getMaxDisp() returns a constrained range.
943 U.KnownAlignment = (KnownBits >= 2);
944
945 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
946 // purposes of the displacement computation; compensate for that here.
947 // For unknown alignments, getMaxDisp() constrains the range instead.
948 if (isThumb && U.KnownAlignment)
949 UserOffset &= ~3u;
950
951 return UserOffset;
952}
953
Jim Grosbach190e7b62012-03-23 23:07:03 +0000954/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000955/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000956/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000957/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000958/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
959/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000960bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000961 unsigned TrialOffset, unsigned MaxDisp,
962 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000963 if (UserOffset <= TrialOffset) {
964 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000965 if (TrialOffset - UserOffset <= MaxDisp)
966 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000967 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000968 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000969 if (UserOffset - TrialOffset <= MaxDisp)
970 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000971 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000972 }
973 return false;
974}
975
Jim Grosbach190e7b62012-03-23 23:07:03 +0000976/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000977/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000978///
979/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000980bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000981 MachineBasicBlock* Water, CPUser &U,
982 unsigned &Growth) {
983 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
984 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
985 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000986 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000987 if (++NextBlock == MF->end()) {
988 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
989 NextBlockAlignment = 0;
990 } else {
991 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
992 NextBlockAlignment = NextBlock->getAlignment();
993 }
994 unsigned Size = U.CPEMI->getOperand(2).getImm();
995 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +0000996
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000997 // The CPE may be able to hide in the alignment padding before the next
998 // block. It may also cause more padding to be required if it is more aligned
999 // that the next block.
1000 if (CPEEnd > NextBlockOffset) {
1001 Growth = CPEEnd - NextBlockOffset;
1002 // Compute the padding that would go at the end of the CPE to align the next
1003 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001004 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001005
1006 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001007 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001008 // in blocks between CPE and the user.
1009 if (CPEOffset < UserOffset)
1010 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1011 } else
1012 // CPE fits in existing padding.
1013 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001014
Jim Grosbach190e7b62012-03-23 23:07:03 +00001015 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001016}
1017
Jim Grosbach190e7b62012-03-23 23:07:03 +00001018/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001019/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001020bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001021 MachineInstr *CPEMI, unsigned MaxDisp,
1022 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001023 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001024
Dale Johannesene18b13b2007-02-23 05:02:36 +00001025 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001026 DEBUG({
1027 unsigned Block = MI->getParent()->getNumber();
1028 const BasicBlockInfo &BBI = BBInfo[Block];
1029 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1030 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001031 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001032 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001033 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1034 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1035 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001036 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001037 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001038
Jim Grosbach190e7b62012-03-23 23:07:03 +00001039 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001040}
1041
Evan Chenge4510972009-01-28 00:53:34 +00001042#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001043/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1044/// unconditionally branches to its only successor.
1045static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1046 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1047 return false;
1048
1049 MachineBasicBlock *Succ = *MBB->succ_begin();
1050 MachineBasicBlock *Pred = *MBB->pred_begin();
1051 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001052 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1053 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001054 return PredMI->getOperand(0).getMBB() == Succ;
1055 return false;
1056}
Evan Chenge4510972009-01-28 00:53:34 +00001057#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001058
Jim Grosbach190e7b62012-03-23 23:07:03 +00001059void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001060 unsigned BBNum = BB->getNumber();
1061 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001062 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001063 // Include the alignment of the current block.
1064 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1065 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1066 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001067
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001068 // This is where block i begins. Stop if the offset is already correct,
1069 // and we have updated 2 blocks. This is the maximum number of blocks
1070 // changed before calling this function.
1071 if (i > BBNum + 2 &&
1072 BBInfo[i].Offset == Offset &&
1073 BBInfo[i].KnownBits == KnownBits)
1074 break;
1075
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001076 BBInfo[i].Offset = Offset;
1077 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001078 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001079}
1080
Jim Grosbach190e7b62012-03-23 23:07:03 +00001081/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001082/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001083/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001084/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001085
Jim Grosbach190e7b62012-03-23 23:07:03 +00001086bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1087 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001088 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001089 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1090 assert(CPE && "Unexpected!");
1091 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001092 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001093 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001094 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001095 return true;
1096 }
1097 return false;
1098}
1099
Tim Northovera603c402015-05-31 19:22:07 +00001100unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1101 if (CPEMI->getOperand(1).isCPI())
1102 return CPEMI->getOperand(1).getIndex();
1103
1104 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1105}
1106
Dale Johannesene18b13b2007-02-23 05:02:36 +00001107/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1108/// if not, see if an in-range clone of the CPE is in range, and if so,
1109/// change the data structures so the user references the clone. Returns:
1110/// 0 = no existing entry found
1111/// 1 = entry found, and there were no code insertions or deletions
1112/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001113int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001114{
1115 MachineInstr *UserMI = U.MI;
1116 MachineInstr *CPEMI = U.CPEMI;
1117
1118 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001119 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1120 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001121 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001122 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001123 }
1124
Dale Johannesene18b13b2007-02-23 05:02:36 +00001125 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001126 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001127 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1128 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1129 // We already tried this one
1130 if (CPEs[i].CPEMI == CPEMI)
1131 continue;
1132 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001133 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001134 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001135 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001136 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001137 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001138 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001139 // Point the CPUser node to the replacement
1140 U.CPEMI = CPEs[i].CPEMI;
1141 // Change the CPI in the instruction operand to refer to the clone.
1142 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001143 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001144 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001145 break;
1146 }
1147 // Adjust the refcount of the clone...
1148 CPEs[i].RefCount++;
1149 // ...and the original. If we didn't remove the old entry, none of the
1150 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001151 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001152 }
1153 }
1154 return 0;
1155}
1156
Dale Johannesen440995b2007-02-28 18:41:23 +00001157/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1158/// the specific unconditional branch instruction.
1159static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001160 switch (Opc) {
1161 case ARM::tB:
1162 return ((1<<10)-1)*2;
1163 case ARM::t2B:
1164 return ((1<<23)-1)*2;
1165 default:
1166 break;
1167 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001168
David Goodwin27303cd2009-06-30 18:04:13 +00001169 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001170}
1171
Jim Grosbach190e7b62012-03-23 23:07:03 +00001172/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001173/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001174/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001175/// is set to the WaterList entry. For Thumb, prefer water that will not
1176/// introduce padding to water that will. To ensure that this pass
1177/// terminates, the CPE location for a particular CPUser is only allowed to
1178/// move to a lower address, so search backward from the end of the list and
1179/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001180bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001181 water_iterator &WaterIter,
1182 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001183 if (WaterList.empty())
1184 return false;
1185
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001186 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001187 // The nearest water without splitting the UserBB is right after it.
1188 // If the distance is still large (we have a big BB), then we need to split it
1189 // if we don't converge after certain iterations. This helps the following
1190 // situation to converge:
1191 // BB0:
1192 // Big BB
1193 // BB1:
1194 // Constant Pool
1195 // When a CP access is out of range, BB0 may be used as water. However,
1196 // inserting islands between BB0 and BB1 makes other accesses out of range.
1197 MachineBasicBlock *UserBB = U.MI->getParent();
1198 unsigned MinNoSplitDisp =
1199 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1200 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1201 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001202 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001203 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001204 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001205 // Check if water is in range and is either at a lower address than the
1206 // current "high water mark" or a new water block that was created since
1207 // the previous iteration by inserting an unconditional branch. In the
1208 // latter case, we want to allow resetting the high water mark back to
1209 // this new water since we haven't seen it before. Inserting branches
1210 // should be relatively uncommon and when it does happen, we want to be
1211 // sure to take advantage of it for all the CPEs near that block, so that
1212 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001213 // When CloserWater is true, we try to find the lowest address after (or
1214 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001215 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001216 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001217 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001218 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1219 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001220 // This is the least amount of required padding seen so far.
1221 BestGrowth = Growth;
1222 WaterIter = IP;
1223 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1224 << " Growth=" << Growth << '\n');
1225
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001226 if (CloserWater && WaterBB == U.MI->getParent())
1227 return true;
1228 // Keep looking unless it is perfect and we're not looking for the lowest
1229 // possible address.
1230 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001231 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001232 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001233 if (IP == B)
1234 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001235 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001236 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001237}
1238
Jim Grosbach190e7b62012-03-23 23:07:03 +00001239/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001240/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1241/// block is used if in range, and the conditional branch munged so control
1242/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001243/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001244/// block following which the new island can be inserted (the WaterList
1245/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001246void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001247 unsigned UserOffset,
1248 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001249 CPUser &U = CPUsers[CPUserIndex];
1250 MachineInstr *UserMI = U.MI;
1251 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001252 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001253 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001254 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001255
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001256 // If the block does not end in an unconditional branch already, and if the
1257 // end of the block is within range, make new water there. (The addition
1258 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001259 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001260 if (BBHasFallthrough(UserMBB)) {
1261 // Size of branch to insert.
1262 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001263 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001264 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001265
Jim Grosbach190e7b62012-03-23 23:07:03 +00001266 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001267 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1268 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001269 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001270 // Add an unconditional branch from UserMBB to fallthrough block. Record
1271 // it for branch lengthening; this new branch will not get out of range,
1272 // but if the preceding conditional branch is out of range, the targets
1273 // will be exchanged, and the altered branch may be out of range, so the
1274 // machinery has to know about it.
1275 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1276 if (!isThumb)
1277 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1278 else
1279 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1280 .addImm(ARMCC::AL).addReg(0);
1281 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1282 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1283 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001284 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001285 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001286 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001287 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001288 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001289
1290 // What a big block. Find a place within the block to split it. This is a
1291 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1292 // entries are 4 bytes: if instruction I references island CPE, and
1293 // instruction I+1 references CPE', it will not work well to put CPE as far
1294 // forward as possible, since then CPE' cannot immediately follow it (that
1295 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1296 // need to create a new island. So, we make a first guess, then walk through
1297 // the instructions between the one currently being looked at and the
1298 // possible insertion point, and make sure any other instructions that
1299 // reference CPEs will be able to use the same island area; if not, we back
1300 // up the insertion point.
1301
1302 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001303 // point where we can add a 4-byte branch instruction, and then align to
1304 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001305 unsigned LogAlign = MF->getAlignment();
1306 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1307 unsigned KnownBits = UserBBI.internalKnownBits();
1308 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001309 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001310 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1311 BaseInsertOffset));
1312
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001313 // The 4 in the following is for the unconditional branch we'll be inserting
1314 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001315 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001316 BaseInsertOffset -= 4;
1317
1318 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1319 << " la=" << LogAlign
1320 << " kb=" << KnownBits
1321 << " up=" << UPad << '\n');
1322
1323 // This could point off the end of the block if we've already got constant
1324 // pool entries following this block; only the last one is in the water list.
1325 // Back past any possible branches (allow for a conditional and a maximally
1326 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001327 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001328 // Ensure BaseInsertOffset is larger than the offset of the instruction
1329 // following UserMI so that the loop which searches for the split point
1330 // iterates at least once.
1331 BaseInsertOffset =
1332 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001333 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001334 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1335 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001336 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001337 CPEMI->getOperand(2).getImm();
1338 MachineBasicBlock::iterator MI = UserMI;
1339 ++MI;
1340 unsigned CPUIndex = CPUserIndex+1;
1341 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001342 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001343 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001344 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001345 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001346 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001347 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001348 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001349 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001350 // Shift intertion point by one unit of alignment so it is within reach.
1351 BaseInsertOffset -= 1u << LogAlign;
1352 EndInsertOffset -= 1u << LogAlign;
1353 }
1354 // This is overly conservative, as we don't account for CPEMIs being
1355 // reused within the block, but it doesn't matter much. Also assume CPEs
1356 // are added in order with alignment padding. We may eventually be able
1357 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001358 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001359 CPUIndex++;
1360 }
1361
1362 // Remember the last IT instruction.
1363 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001364 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001365 }
1366
1367 --MI;
1368
1369 // Avoid splitting an IT block.
1370 if (LastIT) {
1371 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001372 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001373 if (CC != ARMCC::AL)
1374 MI = LastIT;
1375 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001376
1377 // We really must not split an IT block.
1378 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001379 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001380
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001381 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001382}
1383
Jim Grosbach190e7b62012-03-23 23:07:03 +00001384/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001385/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001386/// place in-range. Return true if we changed any addresses (thus must run
1387/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001388bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1389 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001390 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001391 MachineInstr *UserMI = U.MI;
1392 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001393 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001394 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001395 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001396 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001397
Dale Johannesene18b13b2007-02-23 05:02:36 +00001398 // See if the current entry is within range, or there is a clone of it
1399 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001400 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001401 if (result==1) return false;
1402 else if (result==2) return true;
1403
1404 // No existing clone of this CPE is within range.
1405 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001406 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001407
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001408 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001409 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001410 MachineBasicBlock *NewMBB;
1411 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001412 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001413 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001414 MachineBasicBlock *WaterBB = *IP;
1415
1416 // If the original WaterList entry was "new water" on this iteration,
1417 // propagate that to the new island. This is just keeping NewWaterList
1418 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001419 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001420 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001421
Bob Wilson2f9be502009-10-15 20:49:47 +00001422 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001423 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001424 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001425 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001426 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001427 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001428
Jim Grosbach190e7b62012-03-23 23:07:03 +00001429 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001430 // called while handling branches so that the water will be seen on the
1431 // next iteration for constant pools, but in this context, we don't want
1432 // it. Check for this so it will be removed from the WaterList.
1433 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001434 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001435 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001436 if (IP != WaterList.end())
1437 NewWaterList.erase(WaterBB);
1438
1439 // We are adding new water. Update NewWaterList.
1440 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001441 }
1442
Bob Wilson2f9be502009-10-15 20:49:47 +00001443 // Remove the original WaterList entry; we want subsequent insertions in
1444 // this vicinity to go after the one we're about to insert. This
1445 // considerably reduces the number of times we have to move the same CPE
1446 // more than once and is also important to ensure the algorithm terminates.
1447 if (IP != WaterList.end())
1448 WaterList.erase(IP);
1449
Dale Johannesene18b13b2007-02-23 05:02:36 +00001450 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001451 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001452
1453 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001454 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001455
Dale Johannesene18b13b2007-02-23 05:02:36 +00001456 // Now that we have an island to add the CPE to, clone the original CPE and
1457 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001458 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001459 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1460 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001461 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001462 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001463
Tim Northovera603c402015-05-31 19:22:07 +00001464 // Decrement the old entry, and remove it if refcount becomes 0.
1465 decrementCPEReferenceCount(CPI, CPEMI);
1466
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001467 // Mark the basic block as aligned as required by the const-pool entry.
1468 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001469
Evan Cheng10043e22007-01-19 07:51:42 +00001470 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001471 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001472 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001473
Evan Cheng10043e22007-01-19 07:51:42 +00001474 // Finally, change the CPI in the instruction operand to be ID.
1475 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001476 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001477 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001478 break;
1479 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001480
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001481 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001482 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001483
Evan Cheng10043e22007-01-19 07:51:42 +00001484 return true;
1485}
1486
Jim Grosbach190e7b62012-03-23 23:07:03 +00001487/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001488/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001489void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001490 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001491 unsigned Size = CPEMI->getOperand(2).getImm();
1492 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001493 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001494 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001495 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001496 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001497
Evan Chengab28b9a2013-02-21 18:37:54 +00001498 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001499 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001500 } else
1501 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001502 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001503
Jim Grosbach190e7b62012-03-23 23:07:03 +00001504 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001505 // An island has only one predecessor BB and one successor BB. Check if
1506 // this BB's predecessor jumps directly to this BB's successor. This
1507 // shouldn't happen currently.
1508 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1509 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001510}
1511
Jim Grosbach190e7b62012-03-23 23:07:03 +00001512/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001513/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001514bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001515 unsigned MadeChange = false;
1516 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1517 std::vector<CPEntry> &CPEs = CPEntries[i];
1518 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1519 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001520 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001521 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001522 MadeChange = true;
1523 }
1524 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001525 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001526 return MadeChange;
1527}
1528
Jim Grosbach190e7b62012-03-23 23:07:03 +00001529/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001530/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001531bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001532 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001533 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001534 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001535 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001536
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001537 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001538 << " from BB#" << MI->getParent()->getNumber()
1539 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001540 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001541 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001542
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001543 if (BrOffset <= DestOffset) {
1544 // Branch before the Dest.
1545 if (DestOffset-BrOffset <= MaxDisp)
1546 return true;
1547 } else {
1548 if (BrOffset-DestOffset <= MaxDisp)
1549 return true;
1550 }
1551 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001552}
1553
Jim Grosbach190e7b62012-03-23 23:07:03 +00001554/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001555/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001556bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001557 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001558 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001559
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001560 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001561 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001562 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001563
Evan Cheng7fa69642007-01-30 01:18:38 +00001564 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001565 return fixupUnconditionalBr(Br);
1566 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001567}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001568
Jim Grosbach190e7b62012-03-23 23:07:03 +00001569/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001570/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001571/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001572/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001573bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001574ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001575 MachineInstr *MI = Br.MI;
1576 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001577 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001578 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001579
1580 // Use BL to implement far jump.
1581 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001582 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001583 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001584 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001585 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001586 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001587
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001588 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001589
Evan Cheng7fa69642007-01-30 01:18:38 +00001590 return true;
1591}
1592
Jim Grosbach190e7b62012-03-23 23:07:03 +00001593/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001594/// far away to fit in its displacement field. It is converted to an inverse
1595/// conditional branch + an unconditional branch to the destination.
1596bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001597ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001598 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001599 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001600
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001601 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001602 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001603 // blt L1
1604 // =>
1605 // bge L2
1606 // b L1
1607 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001608 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001609 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001610 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001611
1612 // If the branch is at the end of its MBB and that has a fall-through block,
1613 // direct the updated conditional branch to the fall-through block. Otherwise,
1614 // split the MBB before the next instruction.
1615 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001616 MachineInstr *BMI = &MBB->back();
1617 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001618
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001619 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001620 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001621 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001622 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001623 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001624 // condition and swap destinations:
1625 // beq L1
1626 // b L2
1627 // =>
1628 // bne L2
1629 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001630 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001631 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001632 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001633 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001634 BMI->getOperand(0).setMBB(DestBB);
1635 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001636 MI->getOperand(1).setImm(CC);
1637 return true;
1638 }
1639 }
1640 }
1641
1642 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001643 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001644 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001645 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001646 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001647 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001648 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001649 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001650 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001651 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001652
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001653 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001654 << " also invert condition and change dest. to BB#"
1655 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001656
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001657 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001658 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001659 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001660 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001661 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001662 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001663 if (isThumb)
1664 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1665 .addImm(ARMCC::AL).addReg(0);
1666 else
1667 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001668 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001669 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001670 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001671
1672 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001673 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001674 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001675 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001676 return true;
1677}
Evan Cheng7fa69642007-01-30 01:18:38 +00001678
Jim Grosbach190e7b62012-03-23 23:07:03 +00001679/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001680/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1681/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001682bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001683 bool MadeChange = false;
1684 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1685 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001686 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001687 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001688 MI->getOperand(2).getReg() == ARM::PC &&
1689 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001690 // Create the new insn and copy the predicate from the old.
1691 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1692 .addOperand(MI->getOperand(0))
1693 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001694 MI->eraseFromParent();
1695 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001696 }
1697 }
1698 return MadeChange;
1699}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001700
Jim Grosbach190e7b62012-03-23 23:07:03 +00001701bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001702 bool MadeChange = false;
1703
1704 // Shrink ADR and LDR from constantpool.
1705 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1706 CPUser &U = CPUsers[i];
1707 unsigned Opcode = U.MI->getOpcode();
1708 unsigned NewOpc = 0;
1709 unsigned Scale = 1;
1710 unsigned Bits = 0;
1711 switch (Opcode) {
1712 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001713 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLEApcrel;
1716 Bits = 8;
1717 Scale = 4;
1718 }
1719 break;
1720 case ARM::t2LDRpci:
1721 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1722 NewOpc = ARM::tLDRpci;
1723 Bits = 8;
1724 Scale = 4;
1725 }
1726 break;
1727 }
1728
1729 if (!NewOpc)
1730 continue;
1731
Jim Grosbach190e7b62012-03-23 23:07:03 +00001732 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001733 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001734
1735 // Be conservative with inline asm.
1736 if (!U.KnownAlignment)
1737 MaxOffs -= 2;
1738
Evan Chengdb73d682009-08-14 00:32:16 +00001739 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001740 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001741 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001742 U.MI->setDesc(TII->get(NewOpc));
1743 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001744 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001745 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001746 ++NumT2CPShrunk;
1747 MadeChange = true;
1748 }
1749 }
1750
Evan Chengdb73d682009-08-14 00:32:16 +00001751 return MadeChange;
1752}
1753
Jim Grosbach190e7b62012-03-23 23:07:03 +00001754bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001755 bool MadeChange = false;
1756
Peter Collingbourne167668f2015-04-23 20:31:35 +00001757 // The order in which branches appear in ImmBranches is approximately their
1758 // order within the function body. By visiting later branches first, we reduce
1759 // the distance between earlier forward branches and their targets, making it
1760 // more likely that the cbn?z optimization, which can only apply to forward
1761 // branches, will succeed.
1762 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1763 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001764 unsigned Opcode = Br.MI->getOpcode();
1765 unsigned NewOpc = 0;
1766 unsigned Scale = 1;
1767 unsigned Bits = 0;
1768 switch (Opcode) {
1769 default: break;
1770 case ARM::t2B:
1771 NewOpc = ARM::tB;
1772 Bits = 11;
1773 Scale = 2;
1774 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001775 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001776 NewOpc = ARM::tBcc;
1777 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001778 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001779 break;
1780 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001781 }
1782 if (NewOpc) {
1783 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1784 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001785 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001786 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001787 Br.MI->setDesc(TII->get(NewOpc));
1788 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001789 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001790 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001791 ++NumT2BrShrunk;
1792 MadeChange = true;
1793 }
1794 }
1795
1796 Opcode = Br.MI->getOpcode();
1797 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001798 continue;
1799
Evan Cheng6bb95252012-01-14 01:53:46 +00001800 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1801 // so this transformation is not safe.
1802 if (!Br.MI->killsRegister(ARM::CPSR))
1803 continue;
1804
Evan Cheng6f29ad92009-10-31 23:46:45 +00001805 NewOpc = 0;
1806 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001807 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001808 if (Pred == ARMCC::EQ)
1809 NewOpc = ARM::tCBZ;
1810 else if (Pred == ARMCC::NE)
1811 NewOpc = ARM::tCBNZ;
1812 if (!NewOpc)
1813 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001814 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001815 // Check if the distance is within 126. Subtract starting offset by 2
1816 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001817 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001818 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001819 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001820 MachineBasicBlock::iterator CmpMI = Br.MI;
1821 if (CmpMI != Br.MI->getParent()->begin()) {
1822 --CmpMI;
1823 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1824 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001825 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001826 if (Pred == ARMCC::AL &&
1827 CmpMI->getOperand(1).getImm() == 0 &&
1828 isARMLowRegister(Reg)) {
1829 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001830 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001831 MachineInstr *NewBR =
1832 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1833 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1834 CmpMI->eraseFromParent();
1835 Br.MI->eraseFromParent();
1836 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001837 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001838 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001839 ++NumCBZ;
1840 MadeChange = true;
1841 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001842 }
1843 }
Evan Chenge41903b2009-08-14 18:31:44 +00001844 }
1845 }
1846
1847 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001848}
1849
Tim Northovera603c402015-05-31 19:22:07 +00001850static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1851 unsigned BaseReg) {
1852 if (I.getOpcode() != ARM::t2ADDrs)
1853 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001854
Tim Northovera603c402015-05-31 19:22:07 +00001855 if (I.getOperand(0).getReg() != EntryReg)
1856 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001857
Tim Northovera603c402015-05-31 19:22:07 +00001858 if (I.getOperand(1).getReg() != BaseReg)
1859 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001860
Tim Northovera603c402015-05-31 19:22:07 +00001861 // FIXME: what about CC and IdxReg?
1862 return true;
1863}
Tim Northover688f7bb2015-05-13 20:28:32 +00001864
Tim Northovera603c402015-05-31 19:22:07 +00001865/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1866/// doesn't immediately follow the BR_JT) need access to the start of the
1867/// jump-table. We know one instruction that produces such a register; this
1868/// function works out whether that definition can be preserved to the BR_JT,
1869/// possibly by removing an intervening addition (which is usually needed to
1870/// calculate the actual entry to jump to).
1871bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1872 MachineInstr *LEAMI,
1873 unsigned &DeadSize,
1874 bool &CanDeleteLEA,
1875 bool &BaseRegKill) {
1876 if (JumpMI->getParent() != LEAMI->getParent())
1877 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001878
Tim Northovera603c402015-05-31 19:22:07 +00001879 // Now we hope that we have at least these instructions in the basic block:
1880 // BaseReg = t2LEA ...
1881 // [...]
1882 // EntryReg = t2ADDrs BaseReg, ...
1883 // [...]
1884 // t2BR_JT EntryReg
1885 //
1886 // We have to be very conservative about what we recognise here though. The
1887 // main perturbing factors to watch out for are:
1888 // + Spills at any point in the chain: not direct problems but we would
1889 // expect a blocking Def of the spilled register so in practice what we
1890 // can do is limited.
1891 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1892 // of BaseReg, but only if the t2ADDrs can be removed.
1893 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1894 // the wild, but we should be careful.
1895 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1896 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1897
1898 CanDeleteLEA = true;
1899 BaseRegKill = false;
1900 MachineInstr *RemovableAdd = nullptr;
1901 MachineBasicBlock::iterator I(LEAMI);
1902 for (++I; &*I != JumpMI; ++I) {
1903 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1904 RemovableAdd = &*I;
1905 break;
1906 }
1907
1908 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1909 const MachineOperand &MO = I->getOperand(K);
1910 if (!MO.isReg() || !MO.getReg())
1911 continue;
1912 if (MO.isDef() && MO.getReg() == BaseReg)
1913 return false;
1914 if (MO.isUse() && MO.getReg() == BaseReg) {
1915 BaseRegKill = BaseRegKill || MO.isKill();
1916 CanDeleteLEA = false;
1917 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001918 }
1919 }
1920
Tim Northovera603c402015-05-31 19:22:07 +00001921 if (!RemovableAdd)
1922 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001923
Tim Northovera603c402015-05-31 19:22:07 +00001924 // Check the add really is removable, and that nothing else in the block
1925 // clobbers BaseReg.
1926 for (++I; &*I != JumpMI; ++I) {
1927 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1928 const MachineOperand &MO = I->getOperand(K);
1929 if (!MO.isReg() || !MO.getReg())
1930 continue;
1931 if (MO.isDef() && MO.getReg() == BaseReg)
1932 return false;
1933 if (MO.isUse() && MO.getReg() == EntryReg)
1934 RemovableAdd = nullptr;
1935 }
1936 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001937
Tim Northovera603c402015-05-31 19:22:07 +00001938 if (RemovableAdd) {
1939 RemovableAdd->eraseFromParent();
1940 DeadSize += 4;
1941 } else if (BaseReg == EntryReg) {
1942 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1943 // preserve it.
1944 return false;
1945 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001946
Tim Northovera603c402015-05-31 19:22:07 +00001947 // We reached the end of the block without seeing another definition of
1948 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
1949 // used in the TBB/TBH if necessary.
1950 return true;
1951}
Tim Northover688f7bb2015-05-13 20:28:32 +00001952
Tim Northovera603c402015-05-31 19:22:07 +00001953/// \brief Returns whether CPEMI is the first instruction in the block
1954/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
1955/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001956/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00001957static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001958 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00001959 MachineFunction *MF = MBB->getParent();
1960 ++MBB;
1961
1962 return MBB != MF->end() && MBB->begin() != MBB->end() &&
1963 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00001964}
1965
Jim Grosbach190e7b62012-03-23 23:07:03 +00001966/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001967/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001968bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001969 bool MadeChange = false;
1970
1971 // FIXME: After the tables are shrunk, can we get rid some of the
1972 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001973 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001974 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001975
Evan Chengc6d70ae2009-07-29 02:18:14 +00001976 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1977 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1978 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001979 const MCInstrDesc &MCID = MI->getDesc();
1980 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00001981 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00001982 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1983 unsigned JTI = JTOP.getIndex();
1984 assert(JTI < JT.size());
1985
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001986 bool ByteOk = true;
1987 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001988 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00001989 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001990 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1991 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001992 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00001993 // Negative offset is not ok. FIXME: We should change BB layout to make
1994 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00001995 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001996 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00001997 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00001998 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001999 HalfWordOk = false;
2000 if (!ByteOk && !HalfWordOk)
2001 break;
2002 }
2003
Tim Northovera603c402015-05-31 19:22:07 +00002004 if (!ByteOk && !HalfWordOk)
2005 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002006
Tim Northovera603c402015-05-31 19:22:07 +00002007 MachineBasicBlock *MBB = MI->getParent();
2008 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2009 continue;
2010 unsigned IdxReg = MI->getOperand(1).getReg();
2011 bool IdxRegKill = MI->getOperand(1).isKill();
2012
2013 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2014 unsigned DeadSize = 0;
2015 bool CanDeleteLEA = false;
2016 bool BaseRegKill = false;
2017 bool PreservedBaseReg =
2018 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2019
2020 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2021 continue;
2022
2023 DEBUG(dbgs() << "Shrink JT: " << *MI);
2024 MachineInstr *CPEMI = User.CPEMI;
2025 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2026 MachineBasicBlock::iterator MI_JT = MI;
2027 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002028 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002029 .addReg(User.MI->getOperand(0).getReg(),
2030 getKillRegState(BaseRegKill))
2031 .addReg(IdxReg, getKillRegState(IdxRegKill))
2032 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2033 .addImm(CPEMI->getOperand(0).getImm());
2034 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002035
Tim Northovera603c402015-05-31 19:22:07 +00002036 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2037 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002038
Tim Northovera603c402015-05-31 19:22:07 +00002039 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2040 NewJTMI->getOperand(0).setReg(ARM::PC);
2041 NewJTMI->getOperand(0).setIsKill(false);
2042
2043 if (CanDeleteLEA) {
2044 User.MI->eraseFromParent();
2045 DeadSize += 4;
2046
2047 // The LEA was eliminated, the TBB instruction becomes the only new user
2048 // of the jump table.
2049 User.MI = NewJTMI;
2050 User.MaxDisp = 4;
2051 User.NegOk = false;
2052 User.IsSoImm = false;
2053 User.KnownAlignment = false;
2054 } else {
2055 // The LEA couldn't be eliminated, so we must add another CPUser to
2056 // record the TBB or TBH use.
2057 int CPEntryIdx = JumpTableEntryIndices[JTI];
2058 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002059 auto Entry =
2060 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002061 ++Entry->RefCount;
2062 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2063 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002064 }
Tim Northovera603c402015-05-31 19:22:07 +00002065
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002066 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2067 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002068 MI->eraseFromParent();
2069
2070 int Delta = OrigSize - NewSize + DeadSize;
2071 BBInfo[MBB->getNumber()].Size -= Delta;
2072 adjustBBOffsetsAfter(MBB);
2073
2074 ++NumTBs;
2075 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002076 }
2077
2078 return MadeChange;
2079}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002080
Jim Grosbach190e7b62012-03-23 23:07:03 +00002081/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002082/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002083bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002084 bool MadeChange = false;
2085
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002086 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002087 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002088
Jim Grosbach5d577142009-11-12 17:25:07 +00002089 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2090 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2091 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002092 const MCInstrDesc &MCID = MI->getDesc();
2093 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002094 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002095 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2096 unsigned JTI = JTOP.getIndex();
2097 assert(JTI < JT.size());
2098
2099 // We prefer if target blocks for the jump table come after the jump
2100 // instruction so we can use TB[BH]. Loop through the target blocks
2101 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002102 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002103 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2104 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2105 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002106 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002107
Jim Grosbach9785e592009-11-16 18:58:52 +00002108 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002109 // The destination precedes the switch. Try to move the block forward
2110 // so we have a positive offset.
2111 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002112 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002113 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002114 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002115 MadeChange = true;
2116 }
2117 }
2118 }
2119
2120 return MadeChange;
2121}
2122
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002123MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002124adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002125 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002126 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002127 // table that branches back to the actual target. This is a very simple
2128 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002129 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002130 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002131 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002132 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002133 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002134
Jim Grosbach47d5e332009-11-16 17:10:56 +00002135 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002136 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002137
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002138 // If the block ends in an unconditional branch, move it. The prior block
2139 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002140 // 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 +00002141 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002142 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002143 BB->moveAfter(JTBB);
2144 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002145 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002146 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002147 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002148 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002149 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002150 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002151
2152 // Create a new MBB for the code after the jump BB.
2153 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002154 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002155 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002156 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002157
2158 // Add an unconditional branch from NewBB to BB.
2159 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2160 // correspond directly to anything in the source.
2161 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002162 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2163 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002164
Jim Grosbach43d21082009-11-14 20:10:18 +00002165 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002166 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002167
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002168 // Update the CFG.
2169 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002170 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002171
Jim Grosbach5d577142009-11-12 17:25:07 +00002172 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002173 return NewBB;
2174}