blob: 23722f1b7f3ff50b0abb398e33aff04a26760aa0 [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"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000017#include "ARMBaseInstrInfo.h"
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +000018#include "ARMBasicBlockInfo.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000020#include "ARMSubtarget.h"
21#include "MCTargetDesc/ARMBaseInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "Thumb2InstrInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000023#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
Evan Cheng10043e22007-01-19 07:51:42 +000030#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000031#include "llvm/CodeGen/MachineFunction.h"
Evan Cheng10043e22007-01-19 07:51:42 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000033#include "llvm/CodeGen/MachineInstr.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000034#include "llvm/CodeGen/MachineJumpTableInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000035#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000038#include "llvm/IR/DebugLoc.h"
39#include "llvm/MC/MCInstrDesc.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000041#include "llvm/Support/Compiler.h"
Evan Cheng10043e22007-01-19 07:51:42 +000042#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000043#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000044#include "llvm/Support/Format.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000045#include "llvm/Support/MathExtras.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000046#include "llvm/Support/raw_ostream.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000047#include <algorithm>
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000048#include <cassert>
49#include <cstdint>
50#include <iterator>
51#include <new>
52#include <utility>
53#include <vector>
54
Evan Cheng10043e22007-01-19 07:51:42 +000055using namespace llvm;
56
Chandler Carruth84e68b22014-04-22 02:41:26 +000057#define DEBUG_TYPE "arm-cp-islands"
58
James Molloy9b3b8992017-02-13 14:07:25 +000059#define ARM_CP_ISLANDS_OPT_NAME \
60 "ARM constant island placement and branch shortening pass"
Evan Chengdb73d682009-08-14 00:32:16 +000061STATISTIC(NumCPEs, "Number of constpool entries");
62STATISTIC(NumSplit, "Number of uncond branches inserted");
63STATISTIC(NumCBrFixed, "Number of cond branches fixed");
64STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
65STATISTIC(NumTBs, "Number of table branches generated");
66STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000067STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000068STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000069STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000070STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000071
Jim Grosbach8d92ec42009-11-11 02:47:19 +000072static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000073AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000074 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000075
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000076static cl::opt<unsigned>
77CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
78 cl::desc("The max number of iteration for converge"));
79
James Molloy70a3d6d2016-11-01 13:37:41 +000080static cl::opt<bool> SynthesizeThumb1TBB(
81 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
82 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
83 "equivalent to the TBB/TBH instructions"));
84
Evan Cheng10043e22007-01-19 07:51:42 +000085namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000086
Dale Johannesene18b13b2007-02-23 05:02:36 +000087 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000088 /// requires constant pool entries to be scattered among the instructions
89 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000090 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000091 /// special instructions.
92 ///
93 /// The terminology used in this pass includes:
94 /// Islands - Clumps of constants placed in the function.
95 /// Water - Potential places where an island could be formed.
96 /// CPE - A constant pool entry that has been placed somewhere, which
97 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000098 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000099 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000100
Evan Cheng10043e22007-01-19 07:51:42 +0000101 /// WaterList - A sorted list of basic blocks where islands could be placed
102 /// (i.e. blocks that don't fall through to the following block, due
103 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000104 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000105
Bob Wilson2f9be502009-10-15 20:49:47 +0000106 /// NewWaterList - The subset of WaterList that was created since the
107 /// previous iteration by inserting unconditional branches.
108 SmallSet<MachineBasicBlock*, 4> NewWaterList;
109
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000110 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
111
Evan Cheng10043e22007-01-19 07:51:42 +0000112 /// CPUser - One user of a constant pool, keeping the machine instruction
113 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000114 /// allowed from the instruction to the CP. The HighWaterMark records the
115 /// highest basic block where a new CPEntry can be placed. To ensure this
116 /// pass terminates, the CP entries are initially placed at the end of the
117 /// function and then move monotonically to lower addresses. The
118 /// exception to this rule is when the current CP entry for a particular
119 /// CPUser is out of range, but there is another CP entry for the same
120 /// constant value in range. We want to use the existing in-range CP
121 /// entry, but if it later moves out of range, the search for new water
122 /// should resume where it left off. The HighWaterMark is used to record
123 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000124 struct CPUser {
125 MachineInstr *MI;
126 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000127 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000128 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000129 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000130 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000131 bool KnownAlignment;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000132
Evan Chengd2919a12009-07-23 18:27:47 +0000133 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
134 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000135 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
136 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000137 HighWaterMark = CPEMI->getParent();
138 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000139
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000140 /// getMaxDisp - Returns the maximum displacement supported by MI.
141 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000142 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000143 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000144 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000145 }
Evan Cheng10043e22007-01-19 07:51:42 +0000146 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000147
Evan Cheng10043e22007-01-19 07:51:42 +0000148 /// CPUsers - Keep track of all of the machine instructions that use various
149 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000150 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000151
Evan Cheng8b7700f2007-02-09 20:54:44 +0000152 /// CPEntry - One per constant pool entry, keeping the machine instruction
153 /// pointer, the constpool index, and the number of CPUser's which
154 /// reference this entry.
155 struct CPEntry {
156 MachineInstr *CPEMI;
157 unsigned CPI;
158 unsigned RefCount;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000159
Evan Cheng8b7700f2007-02-09 20:54:44 +0000160 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
161 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
162 };
163
164 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000165 /// instructions. For each original constpool index (i.e. those that existed
166 /// upon entry to this pass), it keeps a vector of entries. Original
167 /// elements are cloned as we go along; the clones are put in the vector of
168 /// the original element, but have distinct CPIs.
169 ///
170 /// The first half of CPEntries contains generic constants, the second half
171 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
172 /// which vector it will be in here.
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000173 std::vector<std::vector<CPEntry>> CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000174
Tim Northovera603c402015-05-31 19:22:07 +0000175 /// Maps a JT index to the offset in CPEntries containing copies of that
176 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
177 DenseMap<int, int> JumpTableEntryIndices;
178
179 /// Maps a JT index to the LEA that actually uses the index to calculate its
180 /// base address.
181 DenseMap<int, int> JumpTableUserIndices;
182
Evan Cheng22c7cf52007-01-25 03:12:46 +0000183 /// ImmBranch - One per immediate branch, keeping the machine instruction
184 /// pointer, conditional or unconditional, the max displacement,
185 /// and (if isCond is true) the corresponding unconditional branch
186 /// opcode.
187 struct ImmBranch {
188 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000189 unsigned MaxDisp : 31;
190 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000191 unsigned UncondBr;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000192
Matthias Braunfa3872e2015-05-18 20:27:55 +0000193 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000194 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000195 };
196
Evan Chengc95f95b2007-05-16 05:14:06 +0000197 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000198 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000199 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000200
Evan Cheng7fa69642007-01-30 01:18:38 +0000201 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
202 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000203 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000204
Evan Chengc6d70ae2009-07-29 02:18:14 +0000205 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
206 SmallVector<MachineInstr*, 4> T2JumpTables;
207
Evan Cheng7fa69642007-01-30 01:18:38 +0000208 /// HasFarJump - True if any far jump instruction has been emitted during
209 /// the branch fix up pass.
210 bool HasFarJump;
211
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000212 MachineFunction *MF;
213 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000214 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000215 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000216 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000217 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000218 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000219 bool isThumb2;
James Molloy70a3d6d2016-11-01 13:37:41 +0000220 bool isPositionIndependentOrROPI;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000221
Evan Cheng10043e22007-01-19 07:51:42 +0000222 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000223 static char ID;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000224
Owen Andersona7aed182010-08-06 18:33:48 +0000225 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000226
Craig Topper6bc27bf2014-03-10 02:09:33 +0000227 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000228
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000229 MachineFunctionProperties getRequiredProperties() const override {
230 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000231 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000232 }
233
Mehdi Amini117296c2016-10-01 02:56:57 +0000234 StringRef getPassName() const override {
James Molloy9b3b8992017-02-13 14:07:25 +0000235 return ARM_CP_ISLANDS_OPT_NAME;
Evan Cheng10043e22007-01-19 07:51:42 +0000236 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000237
Evan Cheng10043e22007-01-19 07:51:42 +0000238 private:
Tim Northovera603c402015-05-31 19:22:07 +0000239 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
240 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000241 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000242 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000243 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000244 void scanFunctionJumpTables();
245 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
246 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
247 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
248 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
249 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000250 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000251 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
252 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000253 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000254 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000255 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000256 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000257 void removeDeadCPEMI(MachineInstr *CPEMI);
258 bool removeUnusedCPEntries();
259 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
260 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
261 bool DoDump = false);
262 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000263 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000264 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
265 bool fixupImmediateBr(ImmBranch &Br);
266 bool fixupConditionalBr(ImmBranch &Br);
267 bool fixupUnconditionalBr(ImmBranch &Br);
268 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000269 bool optimizeThumb2Instructions();
270 bool optimizeThumb2Branches();
271 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000272 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
273 unsigned &DeadSize, bool &CanDeleteLEA,
274 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000275 bool optimizeThumb2JumpTables();
276 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000277 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000278
Jim Grosbach190e7b62012-03-23 23:07:03 +0000279 unsigned getOffsetOf(MachineInstr *MI) const;
280 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000281 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000282 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000283
Jim Grosbach190e7b62012-03-23 23:07:03 +0000284 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000285 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000286 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000287 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000288 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000289 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000290 }
Evan Cheng10043e22007-01-19 07:51:42 +0000291 };
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000292
Devang Patel8c78a0b2007-05-03 01:11:54 +0000293 char ARMConstantIslands::ID = 0;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000294
295} // end anonymous namespace
Evan Cheng10043e22007-01-19 07:51:42 +0000296
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000297/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000298void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000299#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000300 assert(std::is_sorted(MF->begin(), MF->end(),
301 [this](const MachineBasicBlock &LHS,
302 const MachineBasicBlock &RHS) {
303 return BBInfo[LHS.getNumber()].postOffset() <
304 BBInfo[RHS.getNumber()].postOffset();
305 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000306 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000307 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
308 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000309 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000310 // Verify offset using the real max displacement without the safety
311 // adjustment.
312 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000313 /* DoDump = */ true)) {
314 DEBUG(dbgs() << "OK\n");
315 continue;
316 }
317 DEBUG(dbgs() << "Out of range.\n");
318 dumpBBs();
319 DEBUG(MF->dump());
320 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000321 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000322#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000323}
324
Matthias Braun8c209aa2017-01-28 02:02:38 +0000325#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000326/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000327LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000328 DEBUG({
329 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
330 const BasicBlockInfo &BBI = BBInfo[J];
331 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
332 << " kb=" << unsigned(BBI.KnownBits)
333 << " ua=" << unsigned(BBI.Unalign)
334 << " pa=" << unsigned(BBI.PostAlign)
335 << format(" size=%#x\n", BBInfo[J].Size);
336 }
337 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000338}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000339#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000340
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000341bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
342 MF = &mf;
343 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000344
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000345 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000346 << MCP->getConstants().size() << " CP entries, aligned to "
347 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000348
Eric Christopher1b21f002015-01-29 00:19:33 +0000349 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
350 TII = STI->getInstrInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +0000351 isPositionIndependentOrROPI =
352 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000353 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000354
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000355 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000356 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000357 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000358
359 HasFarJump = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000360 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
Evan Cheng7fa69642007-01-30 01:18:38 +0000361
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000362 // This pass invalidates liveness information when it splits basic blocks.
363 MF->getRegInfo().invalidateLiveness();
364
Evan Cheng10043e22007-01-19 07:51:42 +0000365 // Renumber all of the machine basic blocks in the function, guaranteeing that
366 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000367 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000368
Jim Grosbach5d577142009-11-12 17:25:07 +0000369 // Try to reorder and otherwise adjust the block layout to make good use
370 // of the TB[BH] instructions.
371 bool MadeChange = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000372 if (GenerateTBB && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000373 scanFunctionJumpTables();
374 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000375 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000376 T2JumpTables.clear();
377 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000378 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000379 }
380
Evan Cheng10043e22007-01-19 07:51:42 +0000381 // Perform the initial placement of the constant pool entries. To start with,
382 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000383 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000384 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000385 doInitialConstPlacement(CPEMIs);
386
387 if (MF->getJumpTableInfo())
388 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000389
Evan Cheng10043e22007-01-19 07:51:42 +0000390 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000391 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000392
Evan Cheng10043e22007-01-19 07:51:42 +0000393 // Do the initial scan of the function, building up information about the
394 // sizes of each block, the location of all the water, and finding all of the
395 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000396 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000397 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000398 DEBUG(dumpBBs());
399
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000400 // Functions with jump tables need an alignment of 4 because they use the ADR
401 // instruction, which aligns the PC to 4 bytes before adding an offset.
402 if (!T2JumpTables.empty())
403 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000404
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000405 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000406 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000407
Evan Cheng7fa69642007-01-30 01:18:38 +0000408 // Iteratively place constant pool entries and fix up branches until there
409 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000410 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000411 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000412 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000413 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000414 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000415 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000416 // If it doesn't end in 10, the input may have huge BB or many CPEs.
417 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000418 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
419 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000420 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000421 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000422
Bob Wilson2f9be502009-10-15 20:49:47 +0000423 // Clear NewWaterList now. If we split a block for branches, it should
424 // appear as "new water" for the next iteration of constant pool placement.
425 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000426
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000427 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000428 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000429 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000430 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000431 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000432 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000433 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000434
435 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000436 break;
437 MadeChange = true;
438 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000439
Bradley Smitha1189102016-01-15 10:26:17 +0000440 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000441 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000442 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000443
Bradley Smitha1189102016-01-15 10:26:17 +0000444 // Shrink 32-bit branch instructions.
445 if (isThumb && STI->hasV8MBaselineOps())
446 MadeChange |= optimizeThumb2Branches();
447
448 // Optimize jump tables using TBB / TBH.
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000449 if (GenerateTBB && !STI->genExecuteOnly())
Bradley Smitha1189102016-01-15 10:26:17 +0000450 MadeChange |= optimizeThumb2JumpTables();
451
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000452 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000453 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000454
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000455 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
456 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000457 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000458 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000459
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000460 // Save the mapping between original and cloned constpool entries.
461 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
462 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
463 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000464 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
465 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000466 }
467 }
468
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000469 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000470
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000471 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000472 WaterList.clear();
473 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000474 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000475 JumpTableEntryIndices.clear();
476 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000477 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000478 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000479 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000480
481 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000482}
483
Tim Northovera603c402015-05-31 19:22:07 +0000484/// \brief Perform the initial placement of the regular constant pool entries.
485/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000486void
Tim Northovera603c402015-05-31 19:22:07 +0000487ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000488 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000489 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
490 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000491
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000492 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000493 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000494
495 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000496 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000497
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000498 // The function needs to be as aligned as the basic blocks. The linker may
499 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000500 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000501
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000502 // Order the entries in BB by descending alignment. That ensures correct
503 // alignment of all entries as long as BB is sufficiently aligned. Keep
504 // track of the insertion point for each alignment. We are going to bucket
505 // sort the entries as they are created.
506 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000507
Evan Cheng10043e22007-01-19 07:51:42 +0000508 // Add all of the constants from the constant pool to the end block, use an
509 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000510 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000511
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000512 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000513 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000514 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000515 assert(Size >= 4 && "Too small constant pool entry");
516 unsigned Align = CPs[i].getAlignment();
517 assert(isPowerOf2_32(Align) && "Invalid alignment");
518 // Verify that all constant pool entries are a multiple of their alignment.
519 // If not, we would have to pad them out so that instructions stay aligned.
520 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
521
522 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
523 unsigned LogAlign = Log2_32(Align);
524 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000525 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000526 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000527 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000528 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000529
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000530 // Ensure that future entries with higher alignment get inserted before
531 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000532 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000533 if (InsPoint[a] == InsAt)
534 InsPoint[a] = CPEMI;
535
Evan Cheng8b7700f2007-02-09 20:54:44 +0000536 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000537 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000538 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000539 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
540 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000541 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000542 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000543}
544
Tim Northovera603c402015-05-31 19:22:07 +0000545/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
546/// instructions can be made more efficient if the jump table immediately
547/// follows the instruction, it's best to place them immediately next to their
548/// jumps to begin with. In almost all cases they'll never be moved from that
549/// position.
550void ARMConstantIslands::doInitialJumpTablePlacement(
551 std::vector<MachineInstr *> &CPEMIs) {
552 unsigned i = CPEntries.size();
553 auto MJTI = MF->getJumpTableInfo();
554 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
555
556 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
557 for (MachineBasicBlock &MBB : *MF) {
558 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000559 if (MI == MBB.end())
560 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000561
562 unsigned JTOpcode;
563 switch (MI->getOpcode()) {
564 default:
565 continue;
566 case ARM::BR_JTadd:
567 case ARM::BR_JTr:
568 case ARM::tBR_JTr:
569 case ARM::BR_JTm:
570 JTOpcode = ARM::JUMPTABLE_ADDRS;
571 break;
572 case ARM::t2BR_JT:
573 JTOpcode = ARM::JUMPTABLE_INSTS;
574 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000575 case ARM::tTBB_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000576 case ARM::t2TBB_JT:
577 JTOpcode = ARM::JUMPTABLE_TBB;
578 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000579 case ARM::tTBH_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000580 case ARM::t2TBH_JT:
581 JTOpcode = ARM::JUMPTABLE_TBH;
582 break;
583 }
584
585 unsigned NumOps = MI->getDesc().getNumOperands();
586 MachineOperand JTOp =
587 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
588 unsigned JTI = JTOp.getIndex();
589 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
590 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
591 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
592 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
593 DebugLoc(), TII->get(JTOpcode))
594 .addImm(i++)
595 .addJumpTableIndex(JTI)
596 .addImm(Size);
597 CPEMIs.push_back(CPEMI);
598 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
599 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
600 if (!LastCorrectlyNumberedBB)
601 LastCorrectlyNumberedBB = &MBB;
602 }
603
604 // If we did anything then we need to renumber the subsequent blocks.
605 if (LastCorrectlyNumberedBB)
606 MF->RenumberBlocks(LastCorrectlyNumberedBB);
607}
608
Dale Johannesene18b13b2007-02-23 05:02:36 +0000609/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000610/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000611bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000612 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000613 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000614 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000615 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000616 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000617
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000618 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000619 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000620 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000621
Tim Northoverab85dcc2014-11-13 17:58:51 +0000622 // Try to analyze the end of the block. A potential fallthrough may already
623 // have an unconditional branch for whatever reason.
624 MachineBasicBlock *TBB, *FBB;
625 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000626 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000627 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000628}
629
Evan Cheng8b7700f2007-02-09 20:54:44 +0000630/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
631/// look up the corresponding CPEntry.
632ARMConstantIslands::CPEntry
633*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
634 const MachineInstr *CPEMI) {
635 std::vector<CPEntry> &CPEs = CPEntries[CPI];
636 // Number of entries per constpool index should be small, just do a
637 // linear search.
638 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
639 if (CPEs[i].CPEMI == CPEMI)
640 return &CPEs[i];
641 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000642 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000643}
644
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000645/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000646/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000647unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000648 switch (CPEMI->getOpcode()) {
649 case ARM::CONSTPOOL_ENTRY:
650 break;
651 case ARM::JUMPTABLE_TBB:
James Molloy70a3d6d2016-11-01 13:37:41 +0000652 return isThumb1 ? 2 : 0;
Tim Northovera603c402015-05-31 19:22:07 +0000653 case ARM::JUMPTABLE_TBH:
James Molloy70a3d6d2016-11-01 13:37:41 +0000654 return isThumb1 ? 2 : 1;
Tim Northovera603c402015-05-31 19:22:07 +0000655 case ARM::JUMPTABLE_INSTS:
656 return 1;
657 case ARM::JUMPTABLE_ADDRS:
658 return 2;
659 default:
660 llvm_unreachable("unknown constpool entry kind");
661 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000662
Tim Northovera603c402015-05-31 19:22:07 +0000663 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000664 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
665 unsigned Align = MCP->getConstants()[CPI].getAlignment();
666 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
667 return Log2_32(Align);
668}
669
Jim Grosbach190e7b62012-03-23 23:07:03 +0000670/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000671/// information about the sizes of each block and the locations of all
672/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000673void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000674 for (MachineBasicBlock &MBB : *MF) {
675 for (MachineInstr &I : MBB)
James Molloy70a3d6d2016-11-01 13:37:41 +0000676 if (I.isBranch() &&
677 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000678 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000679 }
680}
681
Jim Grosbach190e7b62012-03-23 23:07:03 +0000682/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000683/// information about the sizes of each block, the location of all the water,
684/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000685void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000686initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000687
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000688 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000689
690 // The known bits of the entry block offset are determined by the function
691 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000692 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000693
694 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000695 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000696
Bill Wendling18581a42010-12-21 01:54:40 +0000697 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000698 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000699 // If this block doesn't fall through into the next MBB, then this is
700 // 'water' that a constant pool island could be placed.
701 if (!BBHasFallthrough(&MBB))
702 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000703
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000704 for (MachineInstr &I : MBB) {
705 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000706 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000707
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000708 unsigned Opc = I.getOpcode();
709 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000710 bool isCond = false;
711 unsigned Bits = 0;
712 unsigned Scale = 1;
713 int UOpc = Opc;
714 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000715 default:
716 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000717 case ARM::t2BR_JT:
James Molloy70a3d6d2016-11-01 13:37:41 +0000718 case ARM::tBR_JTr:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000719 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000720 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000721 case ARM::Bcc:
722 isCond = true;
723 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000724 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000725 case ARM::B:
726 Bits = 24;
727 Scale = 4;
728 break;
729 case ARM::tBcc:
730 isCond = true;
731 UOpc = ARM::tB;
732 Bits = 8;
733 Scale = 2;
734 break;
735 case ARM::tB:
736 Bits = 11;
737 Scale = 2;
738 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000739 case ARM::t2Bcc:
740 isCond = true;
741 UOpc = ARM::t2B;
742 Bits = 20;
743 Scale = 2;
744 break;
745 case ARM::t2B:
746 Bits = 24;
747 Scale = 2;
748 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000749 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000750
751 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000752 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000753 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000754 }
755
Evan Cheng7fa69642007-01-30 01:18:38 +0000756 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000757 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000758
Tim Northovera603c402015-05-31 19:22:07 +0000759 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
760 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
761 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000762 continue;
763
Evan Cheng10043e22007-01-19 07:51:42 +0000764 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000765 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
766 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000767 // We found one. The addressing mode tells us the max displacement
768 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000769
Evan Cheng10043e22007-01-19 07:51:42 +0000770 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000771 unsigned Bits = 0;
772 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000773 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000774 bool IsSoImm = false;
775
776 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000777 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000778 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000779
780 // Taking the address of a CP entry.
781 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000782 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000783 // This takes a SoImm, which is 8 bit immediate rotated. We'll
784 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000785 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000786 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000787 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000788 Scale = 4;
789 NegOk = true;
790 IsSoImm = true;
791 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000792 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000793 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000794 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000795 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000796 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000797 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000798 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000799 Bits = 8;
800 Scale = 4;
801 break;
802
David Majnemer452f1f92013-06-04 17:46:15 +0000803 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000804 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000805 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000806 case ARM::t2LDRpci:
James Molloy9abb2fa2016-09-26 07:26:24 +0000807 case ARM::t2LDRHpci:
Kristof Beyls5ac6adb2017-02-23 12:24:55 +0000808 case ARM::t2LDRBpci:
Evan Chengfd522992007-02-01 20:44:52 +0000809 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000810 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000811 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000812
813 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000814 Bits = 8;
815 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000816 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000817
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000818 case ARM::VLDRD:
819 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000820 Bits = 8;
821 Scale = 4; // +-(offset_8*4)
822 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000823 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000824
825 case ARM::tLDRHi:
826 Bits = 5;
827 Scale = 2; // +(offset_5*2)
828 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000829 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000830
Evan Cheng10043e22007-01-19 07:51:42 +0000831 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000832 unsigned CPI = I.getOperand(op).getIndex();
833 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000834 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
835 CPI = JumpTableEntryIndices[CPI];
836 }
837
Evan Cheng8b7700f2007-02-09 20:54:44 +0000838 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000839 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000840 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000841
842 // Increment corresponding CPEntry reference count.
843 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
844 assert(CPE && "Cannot find a corresponding CPEntry!");
845 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000846
Evan Cheng10043e22007-01-19 07:51:42 +0000847 // Instructions can only use one CP entry, don't bother scanning the
848 // rest of the operands.
849 break;
850 }
851 }
Evan Cheng10043e22007-01-19 07:51:42 +0000852 }
853}
854
Jim Grosbach190e7b62012-03-23 23:07:03 +0000855/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000856/// from the start of the function. This offset changes as stuff is moved
857/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000858unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000859 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000860
Evan Cheng10043e22007-01-19 07:51:42 +0000861 // The offset is composed of two things: the sum of the sizes of all MBB's
862 // before this instruction's block, and the offset from the start of the block
863 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000864 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000865
866 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000867 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000868 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000869 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000870 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000871 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000872}
873
874/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
875/// ID.
876static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
877 const MachineBasicBlock *RHS) {
878 return LHS->getNumber() < RHS->getNumber();
879}
880
Jim Grosbach190e7b62012-03-23 23:07:03 +0000881/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000882/// machine function, it upsets all of the block numbers. Renumber the blocks
883/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000884void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000885 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000886 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000887
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000888 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000889 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000890 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000891
892 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000893 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000894 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000895 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
896 CompareMBBNumbers);
897 WaterList.insert(IP, NewBB);
898}
899
Evan Cheng10043e22007-01-19 07:51:42 +0000900/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000901/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000902/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000903MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000904 MachineBasicBlock *OrigBB = MI->getParent();
905
906 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000907 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000908 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000909 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000910 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000911
Evan Cheng10043e22007-01-19 07:51:42 +0000912 // Splice the instructions starting with MI over to NewBB.
913 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000914
Evan Cheng10043e22007-01-19 07:51:42 +0000915 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000916 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000917 // There doesn't seem to be meaningful DebugInfo available; this doesn't
918 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000919 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000920 if (!isThumb)
921 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
922 else
Diana Picusbd66b7d2017-01-20 08:15:24 +0000923 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
924 .addMBB(NewBB)
925 .add(predOps(ARMCC::AL));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000926 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000927
Evan Cheng10043e22007-01-19 07:51:42 +0000928 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000929 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000930
Evan Cheng10043e22007-01-19 07:51:42 +0000931 // OrigBB branches to NewBB.
932 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000933
Evan Cheng10043e22007-01-19 07:51:42 +0000934 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000935 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000936 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000937 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000938
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000939 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000940 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000941 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000942
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000943 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000944 // available water after it (but not if it's already there, which happens
945 // when splitting before a conditional branch that is followed by an
946 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000947 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000948 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
949 CompareMBBNumbers);
950 MachineBasicBlock* WaterBB = *IP;
951 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000952 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000953 else
954 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000955 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000956
Dale Johannesenc17dd572010-07-23 22:50:23 +0000957 // Figure out how large the OrigBB is. As the first half of the original
958 // block, it cannot contain a tablejump. The size includes
959 // the new jump we added. (It should be possible to do this without
960 // recounting everything, but it's very confusing, and this is rarely
961 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000962 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000963
Dale Johannesenc17dd572010-07-23 22:50:23 +0000964 // Figure out how large the NewMBB is. As the second half of the original
965 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000966 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000967
Dale Johannesen01ee5752007-02-25 00:47:03 +0000968 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000969 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000970
971 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000972}
973
Jim Grosbach190e7b62012-03-23 23:07:03 +0000974/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000975/// displacement computation. Update U.KnownAlignment to match its current
976/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000977unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
978 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000979 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
980 unsigned KnownBits = BBI.internalKnownBits();
981
982 // The value read from PC is offset from the actual instruction address.
983 UserOffset += (isThumb ? 4 : 8);
984
985 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
986 // Make sure U.getMaxDisp() returns a constrained range.
987 U.KnownAlignment = (KnownBits >= 2);
988
989 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
990 // purposes of the displacement computation; compensate for that here.
991 // For unknown alignments, getMaxDisp() constrains the range instead.
992 if (isThumb && U.KnownAlignment)
993 UserOffset &= ~3u;
994
995 return UserOffset;
996}
997
Jim Grosbach190e7b62012-03-23 23:07:03 +0000998/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000999/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001000/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001001/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001002/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1003/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001004bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001005 unsigned TrialOffset, unsigned MaxDisp,
1006 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001007 if (UserOffset <= TrialOffset) {
1008 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001009 if (TrialOffset - UserOffset <= MaxDisp)
1010 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001011 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001012 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001013 if (UserOffset - TrialOffset <= MaxDisp)
1014 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001015 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001016 }
1017 return false;
1018}
1019
Jim Grosbach190e7b62012-03-23 23:07:03 +00001020/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001021/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001022///
1023/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001024bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001025 MachineBasicBlock* Water, CPUser &U,
1026 unsigned &Growth) {
1027 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1028 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1029 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001030 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001031 if (++NextBlock == MF->end()) {
1032 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1033 NextBlockAlignment = 0;
1034 } else {
1035 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1036 NextBlockAlignment = NextBlock->getAlignment();
1037 }
1038 unsigned Size = U.CPEMI->getOperand(2).getImm();
1039 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001040
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001041 // The CPE may be able to hide in the alignment padding before the next
1042 // block. It may also cause more padding to be required if it is more aligned
1043 // that the next block.
1044 if (CPEEnd > NextBlockOffset) {
1045 Growth = CPEEnd - NextBlockOffset;
1046 // Compute the padding that would go at the end of the CPE to align the next
1047 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001048 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001049
1050 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001051 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001052 // in blocks between CPE and the user.
1053 if (CPEOffset < UserOffset)
1054 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1055 } else
1056 // CPE fits in existing padding.
1057 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001058
Jim Grosbach190e7b62012-03-23 23:07:03 +00001059 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001060}
1061
Jim Grosbach190e7b62012-03-23 23:07:03 +00001062/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001063/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001064bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001065 MachineInstr *CPEMI, unsigned MaxDisp,
1066 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001067 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001068
Dale Johannesene18b13b2007-02-23 05:02:36 +00001069 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001070 DEBUG({
1071 unsigned Block = MI->getParent()->getNumber();
1072 const BasicBlockInfo &BBI = BBInfo[Block];
1073 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1074 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001075 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001076 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001077 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1078 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1079 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001080 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001081 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001082
Jim Grosbach190e7b62012-03-23 23:07:03 +00001083 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001084}
1085
Evan Chenge4510972009-01-28 00:53:34 +00001086#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001087/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1088/// unconditionally branches to its only successor.
1089static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1090 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1091 return false;
1092
1093 MachineBasicBlock *Succ = *MBB->succ_begin();
1094 MachineBasicBlock *Pred = *MBB->pred_begin();
1095 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001096 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1097 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001098 return PredMI->getOperand(0).getMBB() == Succ;
1099 return false;
1100}
Evan Chenge4510972009-01-28 00:53:34 +00001101#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001102
Jim Grosbach190e7b62012-03-23 23:07:03 +00001103void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001104 unsigned BBNum = BB->getNumber();
1105 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001106 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001107 // Include the alignment of the current block.
1108 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1109 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1110 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001111
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001112 // This is where block i begins. Stop if the offset is already correct,
1113 // and we have updated 2 blocks. This is the maximum number of blocks
1114 // changed before calling this function.
1115 if (i > BBNum + 2 &&
1116 BBInfo[i].Offset == Offset &&
1117 BBInfo[i].KnownBits == KnownBits)
1118 break;
1119
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001120 BBInfo[i].Offset = Offset;
1121 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001122 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001123}
1124
Jim Grosbach190e7b62012-03-23 23:07:03 +00001125/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001126/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001127/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001128/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001129
Jim Grosbach190e7b62012-03-23 23:07:03 +00001130bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1131 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001132 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001133 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1134 assert(CPE && "Unexpected!");
1135 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001136 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001137 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001138 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001139 return true;
1140 }
1141 return false;
1142}
1143
Tim Northovera603c402015-05-31 19:22:07 +00001144unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1145 if (CPEMI->getOperand(1).isCPI())
1146 return CPEMI->getOperand(1).getIndex();
1147
1148 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1149}
1150
Dale Johannesene18b13b2007-02-23 05:02:36 +00001151/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1152/// if not, see if an in-range clone of the CPE is in range, and if so,
1153/// change the data structures so the user references the clone. Returns:
1154/// 0 = no existing entry found
1155/// 1 = entry found, and there were no code insertions or deletions
1156/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001157int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001158{
1159 MachineInstr *UserMI = U.MI;
1160 MachineInstr *CPEMI = U.CPEMI;
1161
1162 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001163 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1164 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001165 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001166 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001167 }
1168
Dale Johannesene18b13b2007-02-23 05:02:36 +00001169 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001170 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001171 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1172 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1173 // We already tried this one
1174 if (CPEs[i].CPEMI == CPEMI)
1175 continue;
1176 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001177 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001178 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001179 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001180 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001181 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001182 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001183 // Point the CPUser node to the replacement
1184 U.CPEMI = CPEs[i].CPEMI;
1185 // Change the CPI in the instruction operand to refer to the clone.
1186 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001187 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001188 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001189 break;
1190 }
1191 // Adjust the refcount of the clone...
1192 CPEs[i].RefCount++;
1193 // ...and the original. If we didn't remove the old entry, none of the
1194 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001195 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001196 }
1197 }
1198 return 0;
1199}
1200
Dale Johannesen440995b2007-02-28 18:41:23 +00001201/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1202/// the specific unconditional branch instruction.
1203static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001204 switch (Opc) {
1205 case ARM::tB:
1206 return ((1<<10)-1)*2;
1207 case ARM::t2B:
1208 return ((1<<23)-1)*2;
1209 default:
1210 break;
1211 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001212
David Goodwin27303cd2009-06-30 18:04:13 +00001213 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001214}
1215
Jim Grosbach190e7b62012-03-23 23:07:03 +00001216/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001217/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001218/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001219/// is set to the WaterList entry. For Thumb, prefer water that will not
1220/// introduce padding to water that will. To ensure that this pass
1221/// terminates, the CPE location for a particular CPUser is only allowed to
1222/// move to a lower address, so search backward from the end of the list and
1223/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001224bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001225 water_iterator &WaterIter,
1226 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001227 if (WaterList.empty())
1228 return false;
1229
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001230 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001231 // The nearest water without splitting the UserBB is right after it.
1232 // If the distance is still large (we have a big BB), then we need to split it
1233 // if we don't converge after certain iterations. This helps the following
1234 // situation to converge:
1235 // BB0:
1236 // Big BB
1237 // BB1:
1238 // Constant Pool
1239 // When a CP access is out of range, BB0 may be used as water. However,
1240 // inserting islands between BB0 and BB1 makes other accesses out of range.
1241 MachineBasicBlock *UserBB = U.MI->getParent();
1242 unsigned MinNoSplitDisp =
1243 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1244 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1245 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001246 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001247 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001248 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001249 // Check if water is in range and is either at a lower address than the
1250 // current "high water mark" or a new water block that was created since
1251 // the previous iteration by inserting an unconditional branch. In the
1252 // latter case, we want to allow resetting the high water mark back to
1253 // this new water since we haven't seen it before. Inserting branches
1254 // should be relatively uncommon and when it does happen, we want to be
1255 // sure to take advantage of it for all the CPEs near that block, so that
1256 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001257 // When CloserWater is true, we try to find the lowest address after (or
1258 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001259 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001260 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001261 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001262 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1263 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001264 // This is the least amount of required padding seen so far.
1265 BestGrowth = Growth;
1266 WaterIter = IP;
1267 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1268 << " Growth=" << Growth << '\n');
1269
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001270 if (CloserWater && WaterBB == U.MI->getParent())
1271 return true;
1272 // Keep looking unless it is perfect and we're not looking for the lowest
1273 // possible address.
1274 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001275 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001276 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001277 if (IP == B)
1278 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001279 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001280 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001281}
1282
Jim Grosbach190e7b62012-03-23 23:07:03 +00001283/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001284/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1285/// block is used if in range, and the conditional branch munged so control
1286/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001287/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001288/// block following which the new island can be inserted (the WaterList
1289/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001290void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001291 unsigned UserOffset,
1292 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001293 CPUser &U = CPUsers[CPUserIndex];
1294 MachineInstr *UserMI = U.MI;
1295 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001296 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001297 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001298 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001299
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001300 // If the block does not end in an unconditional branch already, and if the
1301 // end of the block is within range, make new water there. (The addition
1302 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001303 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001304 if (BBHasFallthrough(UserMBB)) {
1305 // Size of branch to insert.
1306 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001307 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001308 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001309
Jim Grosbach190e7b62012-03-23 23:07:03 +00001310 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001311 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1312 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001313 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001314 // Add an unconditional branch from UserMBB to fallthrough block. Record
1315 // it for branch lengthening; this new branch will not get out of range,
1316 // but if the preceding conditional branch is out of range, the targets
1317 // will be exchanged, and the altered branch may be out of range, so the
1318 // machinery has to know about it.
1319 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1320 if (!isThumb)
1321 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1322 else
Diana Picusbd66b7d2017-01-20 08:15:24 +00001323 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1324 .addMBB(NewMBB)
1325 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001326 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1327 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1328 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001329 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001330 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001331 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001332 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001333 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001334
1335 // What a big block. Find a place within the block to split it. This is a
1336 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1337 // entries are 4 bytes: if instruction I references island CPE, and
1338 // instruction I+1 references CPE', it will not work well to put CPE as far
1339 // forward as possible, since then CPE' cannot immediately follow it (that
1340 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1341 // need to create a new island. So, we make a first guess, then walk through
1342 // the instructions between the one currently being looked at and the
1343 // possible insertion point, and make sure any other instructions that
1344 // reference CPEs will be able to use the same island area; if not, we back
1345 // up the insertion point.
1346
1347 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001348 // point where we can add a 4-byte branch instruction, and then align to
1349 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001350 unsigned LogAlign = MF->getAlignment();
1351 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1352 unsigned KnownBits = UserBBI.internalKnownBits();
1353 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001354 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001355 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1356 BaseInsertOffset));
1357
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001358 // The 4 in the following is for the unconditional branch we'll be inserting
1359 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001360 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001361 BaseInsertOffset -= 4;
1362
1363 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1364 << " la=" << LogAlign
1365 << " kb=" << KnownBits
1366 << " up=" << UPad << '\n');
1367
1368 // This could point off the end of the block if we've already got constant
1369 // pool entries following this block; only the last one is in the water list.
1370 // Back past any possible branches (allow for a conditional and a maximally
1371 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001372 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001373 // Ensure BaseInsertOffset is larger than the offset of the instruction
1374 // following UserMI so that the loop which searches for the split point
1375 // iterates at least once.
1376 BaseInsertOffset =
1377 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001378 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001379 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1380 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001381 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001382 CPEMI->getOperand(2).getImm();
1383 MachineBasicBlock::iterator MI = UserMI;
1384 ++MI;
1385 unsigned CPUIndex = CPUserIndex+1;
1386 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001387 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001388 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001389 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001390 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001391 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001392 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001393 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001394 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001395 // Shift intertion point by one unit of alignment so it is within reach.
1396 BaseInsertOffset -= 1u << LogAlign;
1397 EndInsertOffset -= 1u << LogAlign;
1398 }
1399 // This is overly conservative, as we don't account for CPEMIs being
1400 // reused within the block, but it doesn't matter much. Also assume CPEs
1401 // are added in order with alignment padding. We may eventually be able
1402 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001403 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001404 CPUIndex++;
1405 }
1406
1407 // Remember the last IT instruction.
1408 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001409 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001410 }
1411
1412 --MI;
1413
1414 // Avoid splitting an IT block.
1415 if (LastIT) {
1416 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001417 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001418 if (CC != ARMCC::AL)
1419 MI = LastIT;
1420 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001421
1422 // We really must not split an IT block.
1423 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001424 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001425
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001426 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001427}
1428
Jim Grosbach190e7b62012-03-23 23:07:03 +00001429/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001430/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001431/// place in-range. Return true if we changed any addresses (thus must run
1432/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001433bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1434 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001435 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001436 MachineInstr *UserMI = U.MI;
1437 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001438 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001439 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001440 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001441 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001442
Dale Johannesene18b13b2007-02-23 05:02:36 +00001443 // See if the current entry is within range, or there is a clone of it
1444 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001445 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001446 if (result==1) return false;
1447 else if (result==2) return true;
1448
1449 // No existing clone of this CPE is within range.
1450 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001451 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001452
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001453 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001454 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001455 MachineBasicBlock *NewMBB;
1456 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001457 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001458 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001459 MachineBasicBlock *WaterBB = *IP;
1460
1461 // If the original WaterList entry was "new water" on this iteration,
1462 // propagate that to the new island. This is just keeping NewWaterList
1463 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001464 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001465 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001466
Bob Wilson2f9be502009-10-15 20:49:47 +00001467 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001468 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001469 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001470 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001471 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001472 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001473
Jim Grosbach190e7b62012-03-23 23:07:03 +00001474 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001475 // called while handling branches so that the water will be seen on the
1476 // next iteration for constant pools, but in this context, we don't want
1477 // it. Check for this so it will be removed from the WaterList.
1478 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001479 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001480 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001481 if (IP != WaterList.end())
1482 NewWaterList.erase(WaterBB);
1483
1484 // We are adding new water. Update NewWaterList.
1485 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001486 }
1487
Bob Wilson2f9be502009-10-15 20:49:47 +00001488 // Remove the original WaterList entry; we want subsequent insertions in
1489 // this vicinity to go after the one we're about to insert. This
1490 // considerably reduces the number of times we have to move the same CPE
1491 // more than once and is also important to ensure the algorithm terminates.
1492 if (IP != WaterList.end())
1493 WaterList.erase(IP);
1494
Dale Johannesene18b13b2007-02-23 05:02:36 +00001495 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001496 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001497
1498 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001499 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001500
Dale Johannesene18b13b2007-02-23 05:02:36 +00001501 // Now that we have an island to add the CPE to, clone the original CPE and
1502 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001503 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001504 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
Diana Picus116bbab2017-01-13 09:58:52 +00001505 .addImm(ID)
1506 .add(CPEMI->getOperand(1))
1507 .addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001508 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001509 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001510
Tim Northovera603c402015-05-31 19:22:07 +00001511 // Decrement the old entry, and remove it if refcount becomes 0.
1512 decrementCPEReferenceCount(CPI, CPEMI);
1513
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001514 // Mark the basic block as aligned as required by the const-pool entry.
1515 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001516
Evan Cheng10043e22007-01-19 07:51:42 +00001517 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001518 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001519 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001520
Evan Cheng10043e22007-01-19 07:51:42 +00001521 // Finally, change the CPI in the instruction operand to be ID.
1522 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001523 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001524 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001525 break;
1526 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001527
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001528 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001529 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001530
Evan Cheng10043e22007-01-19 07:51:42 +00001531 return true;
1532}
1533
Jim Grosbach190e7b62012-03-23 23:07:03 +00001534/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001535/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001536void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001537 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001538 unsigned Size = CPEMI->getOperand(2).getImm();
1539 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001540 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001541 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001542 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001543 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001544
Evan Chengab28b9a2013-02-21 18:37:54 +00001545 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001546 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001547 } else
1548 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001549 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001550
Jim Grosbach190e7b62012-03-23 23:07:03 +00001551 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001552 // An island has only one predecessor BB and one successor BB. Check if
1553 // this BB's predecessor jumps directly to this BB's successor. This
1554 // shouldn't happen currently.
1555 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1556 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001557}
1558
Jim Grosbach190e7b62012-03-23 23:07:03 +00001559/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001560/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001561bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001562 unsigned MadeChange = false;
1563 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1564 std::vector<CPEntry> &CPEs = CPEntries[i];
1565 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1566 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001567 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001568 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001569 MadeChange = true;
1570 }
1571 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001572 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001573 return MadeChange;
1574}
1575
Jim Grosbach190e7b62012-03-23 23:07:03 +00001576/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001577/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001578bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001579 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001580 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001581 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001582 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001583
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001584 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001585 << " from BB#" << MI->getParent()->getNumber()
1586 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001587 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001588 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001589
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001590 if (BrOffset <= DestOffset) {
1591 // Branch before the Dest.
1592 if (DestOffset-BrOffset <= MaxDisp)
1593 return true;
1594 } else {
1595 if (BrOffset-DestOffset <= MaxDisp)
1596 return true;
1597 }
1598 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001599}
1600
Jim Grosbach190e7b62012-03-23 23:07:03 +00001601/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001602/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001603bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001604 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001605 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001606
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001607 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001608 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001609 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001610
Evan Cheng7fa69642007-01-30 01:18:38 +00001611 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001612 return fixupUnconditionalBr(Br);
1613 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001614}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001615
Jim Grosbach190e7b62012-03-23 23:07:03 +00001616/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001617/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001618/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001619/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001620bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001621ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001622 MachineInstr *MI = Br.MI;
1623 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001624 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001625 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001626
1627 // Use BL to implement far jump.
1628 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001629 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001630 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001631 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001632 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001633 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001634
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001635 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001636
Evan Cheng7fa69642007-01-30 01:18:38 +00001637 return true;
1638}
1639
Jim Grosbach190e7b62012-03-23 23:07:03 +00001640/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001641/// far away to fit in its displacement field. It is converted to an inverse
1642/// conditional branch + an unconditional branch to the destination.
1643bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001644ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001645 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001646 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001647
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001648 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001649 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001650 // blt L1
1651 // =>
1652 // bge L2
1653 // b L1
1654 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001655 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001656 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001657 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001658
1659 // If the branch is at the end of its MBB and that has a fall-through block,
1660 // direct the updated conditional branch to the fall-through block. Otherwise,
1661 // split the MBB before the next instruction.
1662 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001663 MachineInstr *BMI = &MBB->back();
1664 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001665
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001666 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001667 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001668 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001669 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001670 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001671 // condition and swap destinations:
1672 // beq L1
1673 // b L2
1674 // =>
1675 // bne L2
1676 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001677 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001678 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001679 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001680 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001681 BMI->getOperand(0).setMBB(DestBB);
1682 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001683 MI->getOperand(1).setImm(CC);
1684 return true;
1685 }
1686 }
1687 }
1688
1689 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001690 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001691 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001692 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001693 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001694 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001695 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001696 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001697 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001698 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001699
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001700 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001701 << " also invert condition and change dest. to BB#"
1702 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001703
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001704 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001705 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001706 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001707 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001708 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001709 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001710 if (isThumb)
Diana Picusbd66b7d2017-01-20 08:15:24 +00001711 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1712 .addMBB(DestBB)
1713 .add(predOps(ARMCC::AL));
Owen Anderson93cd3182011-09-09 23:05:14 +00001714 else
1715 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001716 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001717 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001718 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001719
1720 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001721 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001722 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001723 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001724 return true;
1725}
Evan Cheng7fa69642007-01-30 01:18:38 +00001726
Jim Grosbach190e7b62012-03-23 23:07:03 +00001727/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001728/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1729/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001730bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001731 bool MadeChange = false;
1732 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1733 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001734 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001735 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001736 MI->getOperand(2).getReg() == ARM::PC &&
1737 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001738 // Create the new insn and copy the predicate from the old.
1739 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
Diana Picus116bbab2017-01-13 09:58:52 +00001740 .add(MI->getOperand(0))
1741 .add(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001742 MI->eraseFromParent();
1743 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001744 }
Roger Ferrer Ibanez56db97d2017-02-22 09:06:21 +00001745 if (MI->getOpcode() == ARM::tPUSH &&
1746 MI->getOperand(2).getReg() == ARM::LR &&
1747 MI->getNumExplicitOperands() == 3) {
1748 // Just remove the push.
1749 MI->eraseFromParent();
1750 MadeChange = true;
1751 }
Evan Cheng7fa69642007-01-30 01:18:38 +00001752 }
1753 return MadeChange;
1754}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001755
Jim Grosbach190e7b62012-03-23 23:07:03 +00001756bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001757 bool MadeChange = false;
1758
1759 // Shrink ADR and LDR from constantpool.
1760 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1761 CPUser &U = CPUsers[i];
1762 unsigned Opcode = U.MI->getOpcode();
1763 unsigned NewOpc = 0;
1764 unsigned Scale = 1;
1765 unsigned Bits = 0;
1766 switch (Opcode) {
1767 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001768 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001769 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1770 NewOpc = ARM::tLEApcrel;
1771 Bits = 8;
1772 Scale = 4;
1773 }
1774 break;
1775 case ARM::t2LDRpci:
1776 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1777 NewOpc = ARM::tLDRpci;
1778 Bits = 8;
1779 Scale = 4;
1780 }
1781 break;
1782 }
1783
1784 if (!NewOpc)
1785 continue;
1786
Jim Grosbach190e7b62012-03-23 23:07:03 +00001787 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001788 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001789
1790 // Be conservative with inline asm.
1791 if (!U.KnownAlignment)
1792 MaxOffs -= 2;
1793
Evan Chengdb73d682009-08-14 00:32:16 +00001794 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001795 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001796 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001797 U.MI->setDesc(TII->get(NewOpc));
1798 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001799 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001800 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001801 ++NumT2CPShrunk;
1802 MadeChange = true;
1803 }
1804 }
1805
Evan Chengdb73d682009-08-14 00:32:16 +00001806 return MadeChange;
1807}
1808
Jim Grosbach190e7b62012-03-23 23:07:03 +00001809bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001810 bool MadeChange = false;
1811
Peter Collingbourne167668f2015-04-23 20:31:35 +00001812 // The order in which branches appear in ImmBranches is approximately their
1813 // order within the function body. By visiting later branches first, we reduce
1814 // the distance between earlier forward branches and their targets, making it
1815 // more likely that the cbn?z optimization, which can only apply to forward
1816 // branches, will succeed.
1817 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1818 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001819 unsigned Opcode = Br.MI->getOpcode();
1820 unsigned NewOpc = 0;
1821 unsigned Scale = 1;
1822 unsigned Bits = 0;
1823 switch (Opcode) {
1824 default: break;
1825 case ARM::t2B:
1826 NewOpc = ARM::tB;
1827 Bits = 11;
1828 Scale = 2;
1829 break;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001830 case ARM::t2Bcc:
Evan Chenge41903b2009-08-14 18:31:44 +00001831 NewOpc = ARM::tBcc;
1832 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001833 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001834 break;
1835 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001836 if (NewOpc) {
1837 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1838 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001839 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001840 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001841 Br.MI->setDesc(TII->get(NewOpc));
1842 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001843 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001844 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001845 ++NumT2BrShrunk;
1846 MadeChange = true;
1847 }
1848 }
1849
1850 Opcode = Br.MI->getOpcode();
1851 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001852 continue;
1853
Evan Cheng6bb95252012-01-14 01:53:46 +00001854 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1855 // so this transformation is not safe.
1856 if (!Br.MI->killsRegister(ARM::CPSR))
1857 continue;
1858
Evan Cheng6f29ad92009-10-31 23:46:45 +00001859 NewOpc = 0;
1860 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001861 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001862 if (Pred == ARMCC::EQ)
1863 NewOpc = ARM::tCBZ;
1864 else if (Pred == ARMCC::NE)
1865 NewOpc = ARM::tCBNZ;
1866 if (!NewOpc)
1867 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001868 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001869 // Check if the distance is within 126. Subtract starting offset by 2
1870 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001871 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001872 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001873 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001874 MachineBasicBlock::iterator CmpMI = Br.MI;
1875 if (CmpMI != Br.MI->getParent()->begin()) {
1876 --CmpMI;
1877 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1878 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001879 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001880 if (Pred == ARMCC::AL &&
1881 CmpMI->getOperand(1).getImm() == 0 &&
1882 isARMLowRegister(Reg)) {
1883 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001884 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001885 MachineInstr *NewBR =
1886 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1887 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1888 CmpMI->eraseFromParent();
1889 Br.MI->eraseFromParent();
1890 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001891 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001892 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001893 ++NumCBZ;
1894 MadeChange = true;
1895 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001896 }
1897 }
Evan Chenge41903b2009-08-14 18:31:44 +00001898 }
1899 }
1900
1901 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001902}
1903
Tim Northovera603c402015-05-31 19:22:07 +00001904static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1905 unsigned BaseReg) {
1906 if (I.getOpcode() != ARM::t2ADDrs)
1907 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001908
Tim Northovera603c402015-05-31 19:22:07 +00001909 if (I.getOperand(0).getReg() != EntryReg)
1910 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001911
Tim Northovera603c402015-05-31 19:22:07 +00001912 if (I.getOperand(1).getReg() != BaseReg)
1913 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001914
Tim Northovera603c402015-05-31 19:22:07 +00001915 // FIXME: what about CC and IdxReg?
1916 return true;
1917}
Tim Northover688f7bb2015-05-13 20:28:32 +00001918
Tim Northovera603c402015-05-31 19:22:07 +00001919/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1920/// doesn't immediately follow the BR_JT) need access to the start of the
1921/// jump-table. We know one instruction that produces such a register; this
1922/// function works out whether that definition can be preserved to the BR_JT,
1923/// possibly by removing an intervening addition (which is usually needed to
1924/// calculate the actual entry to jump to).
1925bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1926 MachineInstr *LEAMI,
1927 unsigned &DeadSize,
1928 bool &CanDeleteLEA,
1929 bool &BaseRegKill) {
1930 if (JumpMI->getParent() != LEAMI->getParent())
1931 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001932
Tim Northovera603c402015-05-31 19:22:07 +00001933 // Now we hope that we have at least these instructions in the basic block:
1934 // BaseReg = t2LEA ...
1935 // [...]
1936 // EntryReg = t2ADDrs BaseReg, ...
1937 // [...]
1938 // t2BR_JT EntryReg
1939 //
1940 // We have to be very conservative about what we recognise here though. The
1941 // main perturbing factors to watch out for are:
1942 // + Spills at any point in the chain: not direct problems but we would
1943 // expect a blocking Def of the spilled register so in practice what we
1944 // can do is limited.
1945 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1946 // of BaseReg, but only if the t2ADDrs can be removed.
1947 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1948 // the wild, but we should be careful.
1949 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1950 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1951
1952 CanDeleteLEA = true;
1953 BaseRegKill = false;
1954 MachineInstr *RemovableAdd = nullptr;
1955 MachineBasicBlock::iterator I(LEAMI);
1956 for (++I; &*I != JumpMI; ++I) {
1957 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1958 RemovableAdd = &*I;
1959 break;
1960 }
1961
1962 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1963 const MachineOperand &MO = I->getOperand(K);
1964 if (!MO.isReg() || !MO.getReg())
1965 continue;
1966 if (MO.isDef() && MO.getReg() == BaseReg)
1967 return false;
1968 if (MO.isUse() && MO.getReg() == BaseReg) {
1969 BaseRegKill = BaseRegKill || MO.isKill();
1970 CanDeleteLEA = false;
1971 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001972 }
1973 }
1974
Tim Northovera603c402015-05-31 19:22:07 +00001975 if (!RemovableAdd)
1976 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001977
Tim Northovera603c402015-05-31 19:22:07 +00001978 // Check the add really is removable, and that nothing else in the block
1979 // clobbers BaseReg.
1980 for (++I; &*I != JumpMI; ++I) {
1981 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1982 const MachineOperand &MO = I->getOperand(K);
1983 if (!MO.isReg() || !MO.getReg())
1984 continue;
1985 if (MO.isDef() && MO.getReg() == BaseReg)
1986 return false;
1987 if (MO.isUse() && MO.getReg() == EntryReg)
1988 RemovableAdd = nullptr;
1989 }
1990 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001991
Tim Northovera603c402015-05-31 19:22:07 +00001992 if (RemovableAdd) {
1993 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00001994 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00001995 } else if (BaseReg == EntryReg) {
1996 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1997 // preserve it.
1998 return false;
1999 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002000
Tim Northovera603c402015-05-31 19:22:07 +00002001 // We reached the end of the block without seeing another definition of
2002 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2003 // used in the TBB/TBH if necessary.
2004 return true;
2005}
Tim Northover688f7bb2015-05-13 20:28:32 +00002006
Tim Northovera603c402015-05-31 19:22:07 +00002007/// \brief Returns whether CPEMI is the first instruction in the block
2008/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2009/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002010/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002011static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002012 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002013 MachineFunction *MF = MBB->getParent();
2014 ++MBB;
2015
2016 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2017 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002018}
2019
David Green1b4b59a2017-04-06 08:32:47 +00002020static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
2021 MachineInstr *JumpMI,
2022 unsigned &DeadSize) {
2023 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2024 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2025 // and is not clobbered / used.
2026 MachineInstr *RemovableAdd = nullptr;
2027 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2028
2029 // Find the last ADD to set EntryReg
2030 MachineBasicBlock::iterator I(LEAMI);
2031 for (++I; &*I != JumpMI; ++I) {
2032 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2033 RemovableAdd = &*I;
2034 }
2035
2036 if (!RemovableAdd)
2037 return;
2038
2039 // Ensure EntryReg is not clobbered or used.
2040 MachineBasicBlock::iterator J(RemovableAdd);
2041 for (++J; &*J != JumpMI; ++J) {
2042 for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2043 const MachineOperand &MO = J->getOperand(K);
2044 if (!MO.isReg() || !MO.getReg())
2045 continue;
2046 if (MO.isDef() && MO.getReg() == EntryReg)
2047 return;
2048 if (MO.isUse() && MO.getReg() == EntryReg)
2049 return;
2050 }
2051 }
2052
2053 DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
2054 RemovableAdd->eraseFromParent();
2055 DeadSize += 4;
2056}
2057
James Molloy92497542017-02-13 14:07:39 +00002058static bool registerDefinedBetween(unsigned Reg,
2059 MachineBasicBlock::iterator From,
2060 MachineBasicBlock::iterator To,
2061 const TargetRegisterInfo *TRI) {
2062 for (auto I = From; I != To; ++I)
2063 if (I->modifiesRegister(Reg, TRI))
2064 return true;
2065 return false;
2066}
2067
Jim Grosbach190e7b62012-03-23 23:07:03 +00002068/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002069/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002070bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002071 bool MadeChange = false;
2072
2073 // FIXME: After the tables are shrunk, can we get rid some of the
2074 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002075 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002076 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002077
Evan Chengc6d70ae2009-07-29 02:18:14 +00002078 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2079 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2080 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002081 const MCInstrDesc &MCID = MI->getDesc();
2082 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002083 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002084 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2085 unsigned JTI = JTOP.getIndex();
2086 assert(JTI < JT.size());
2087
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002088 bool ByteOk = true;
2089 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002090 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002091 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002092 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2093 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002094 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002095 // Negative offset is not ok. FIXME: We should change BB layout to make
2096 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002097 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002098 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002099 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002100 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002101 HalfWordOk = false;
2102 if (!ByteOk && !HalfWordOk)
2103 break;
2104 }
2105
Tim Northovera603c402015-05-31 19:22:07 +00002106 if (!ByteOk && !HalfWordOk)
2107 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002108
James Molloy70a3d6d2016-11-01 13:37:41 +00002109 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002110 MachineBasicBlock *MBB = MI->getParent();
2111 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2112 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002113
Tim Northovera603c402015-05-31 19:22:07 +00002114 unsigned DeadSize = 0;
2115 bool CanDeleteLEA = false;
2116 bool BaseRegKill = false;
James Molloy70a3d6d2016-11-01 13:37:41 +00002117
2118 unsigned IdxReg = ~0U;
2119 bool IdxRegKill = true;
2120 if (isThumb2) {
2121 IdxReg = MI->getOperand(1).getReg();
2122 IdxRegKill = MI->getOperand(1).isKill();
2123
2124 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002125 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002126 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2127 continue;
2128 } else {
2129 // We're in thumb-1 mode, so we must have something like:
2130 // %idx = tLSLri %idx, 2
2131 // %base = tLEApcrelJT
2132 // %t = tLDRr %idx, %base
2133 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002134
James Molloy70a3d6d2016-11-01 13:37:41 +00002135 if (User.MI->getIterator() == User.MI->getParent()->begin())
2136 continue;
2137 MachineInstr *Shift = User.MI->getPrevNode();
2138 if (Shift->getOpcode() != ARM::tLSLri ||
2139 Shift->getOperand(3).getImm() != 2 ||
2140 !Shift->getOperand(2).isKill())
2141 continue;
2142 IdxReg = Shift->getOperand(2).getReg();
2143 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002144
Tim Northover0d98b032017-03-15 18:38:13 +00002145 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2146 // the range is checked later, but the LEA might still clobber it and not
2147 // actually get removed.
2148 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2149 continue;
2150
James Molloy70a3d6d2016-11-01 13:37:41 +00002151 MachineInstr *Load = User.MI->getNextNode();
2152 if (Load->getOpcode() != ARM::tLDRr)
2153 continue;
2154 if (Load->getOperand(1).getReg() != ShiftedIdxReg ||
2155 Load->getOperand(2).getReg() != BaseReg ||
2156 !Load->getOperand(1).isKill())
2157 continue;
2158
2159 // If we're in PIC mode, there should be another ADD following.
James Molloy92497542017-02-13 14:07:39 +00002160 auto *TRI = STI->getRegisterInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +00002161 if (isPositionIndependentOrROPI) {
2162 MachineInstr *Add = Load->getNextNode();
2163 if (Add->getOpcode() != ARM::tADDrr ||
2164 Add->getOperand(2).getReg() != Load->getOperand(0).getReg() ||
2165 Add->getOperand(3).getReg() != BaseReg ||
2166 !Add->getOperand(2).isKill())
2167 continue;
2168 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2169 continue;
James Molloy92497542017-02-13 14:07:39 +00002170 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2171 // IdxReg gets redefined in the middle of the sequence.
2172 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002173 Add->eraseFromParent();
2174 DeadSize += 2;
2175 } else {
2176 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2177 continue;
James Molloy92497542017-02-13 14:07:39 +00002178 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2179 // IdxReg gets redefined in the middle of the sequence.
2180 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002181 }
Tim Northover0d98b032017-03-15 18:38:13 +00002182
James Molloy70a3d6d2016-11-01 13:37:41 +00002183 // Now safe to delete the load and lsl. The LEA will be removed later.
2184 CanDeleteLEA = true;
2185 Shift->eraseFromParent();
2186 Load->eraseFromParent();
2187 DeadSize += 4;
2188 }
Tim Northover0d98b032017-03-15 18:38:13 +00002189
Tim Northovera603c402015-05-31 19:22:07 +00002190 DEBUG(dbgs() << "Shrink JT: " << *MI);
2191 MachineInstr *CPEMI = User.CPEMI;
2192 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002193 if (!isThumb2)
2194 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2195
Tim Northovera603c402015-05-31 19:22:07 +00002196 MachineBasicBlock::iterator MI_JT = MI;
2197 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002198 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002199 .addReg(User.MI->getOperand(0).getReg(),
2200 getKillRegState(BaseRegKill))
2201 .addReg(IdxReg, getKillRegState(IdxRegKill))
2202 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2203 .addImm(CPEMI->getOperand(0).getImm());
2204 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002205
Tim Northovera603c402015-05-31 19:22:07 +00002206 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2207 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002208
Tim Northovera603c402015-05-31 19:22:07 +00002209 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2210 NewJTMI->getOperand(0).setReg(ARM::PC);
2211 NewJTMI->getOperand(0).setIsKill(false);
2212
David Green1b4b59a2017-04-06 08:32:47 +00002213 if (CanDeleteLEA) {
2214 if (isThumb2)
2215 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2216
Tim Northovera603c402015-05-31 19:22:07 +00002217 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002218 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002219
2220 // The LEA was eliminated, the TBB instruction becomes the only new user
2221 // of the jump table.
2222 User.MI = NewJTMI;
2223 User.MaxDisp = 4;
2224 User.NegOk = false;
2225 User.IsSoImm = false;
2226 User.KnownAlignment = false;
2227 } else {
2228 // The LEA couldn't be eliminated, so we must add another CPUser to
2229 // record the TBB or TBH use.
2230 int CPEntryIdx = JumpTableEntryIndices[JTI];
2231 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002232 auto Entry =
2233 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002234 ++Entry->RefCount;
2235 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2236 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002237 }
Tim Northovera603c402015-05-31 19:22:07 +00002238
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002239 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2240 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002241 MI->eraseFromParent();
2242
2243 int Delta = OrigSize - NewSize + DeadSize;
2244 BBInfo[MBB->getNumber()].Size -= Delta;
2245 adjustBBOffsetsAfter(MBB);
2246
2247 ++NumTBs;
2248 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002249 }
2250
2251 return MadeChange;
2252}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002253
Jim Grosbach190e7b62012-03-23 23:07:03 +00002254/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002255/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002256bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002257 bool MadeChange = false;
2258
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002259 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002260 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002261
Jim Grosbach5d577142009-11-12 17:25:07 +00002262 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2263 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2264 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002265 const MCInstrDesc &MCID = MI->getDesc();
2266 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002267 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002268 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2269 unsigned JTI = JTOP.getIndex();
2270 assert(JTI < JT.size());
2271
2272 // We prefer if target blocks for the jump table come after the jump
2273 // instruction so we can use TB[BH]. Loop through the target blocks
2274 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002275 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002276 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2277 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2278 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002279 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002280
Jim Grosbach9785e592009-11-16 18:58:52 +00002281 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002282 // The destination precedes the switch. Try to move the block forward
2283 // so we have a positive offset.
2284 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002285 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002286 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002287 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002288 MadeChange = true;
2289 }
2290 }
2291 }
2292
2293 return MadeChange;
2294}
2295
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002296MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002297adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002298 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002299 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002300 // table that branches back to the actual target. This is a very simple
2301 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002302 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002303 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002304 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002305 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002306 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002307
Jim Grosbach47d5e332009-11-16 17:10:56 +00002308 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002309 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002310
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002311 // If the block ends in an unconditional branch, move it. The prior block
2312 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002313 // 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 +00002314 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002315 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002316 BB->moveAfter(JTBB);
2317 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002318 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002319 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002320 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002321 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002322 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002323 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002324
2325 // Create a new MBB for the code after the jump BB.
2326 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002327 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002328 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002329 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002330
2331 // Add an unconditional branch from NewBB to BB.
2332 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2333 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002334 if (isThumb2)
2335 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2336 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002337 .add(predOps(ARMCC::AL));
James Molloy70a3d6d2016-11-01 13:37:41 +00002338 else
2339 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2340 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002341 .add(predOps(ARMCC::AL));
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002342
Jim Grosbach43d21082009-11-14 20:10:18 +00002343 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002344 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002345
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002346 // Update the CFG.
2347 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002348 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002349
Jim Grosbach5d577142009-11-12 17:25:07 +00002350 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002351 return NewBB;
2352}
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002353
2354/// createARMConstantIslandPass - returns an instance of the constpool
2355/// island pass.
2356FunctionPass *llvm::createARMConstantIslandPass() {
2357 return new ARMConstantIslands();
2358}
James Molloy9b3b8992017-02-13 14:07:25 +00002359
2360INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2361 false, false)