blob: 5e97c4cb35e3636ab8f1ded5839c0145d83b91d0 [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +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 Zelenko076468c2017-09-20 21:35:51 +000023#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000024#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000029#include "llvm/ADT/StringRef.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
Evan Cheng10043e22007-01-19 07:51:42 +000031#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000032#include "llvm/CodeGen/MachineFunction.h"
Evan Cheng10043e22007-01-19 07:51:42 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000034#include "llvm/CodeGen/MachineInstr.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000035#include "llvm/CodeGen/MachineJumpTableInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000036#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000038#include "llvm/Config/llvm-config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DataLayout.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000040#include "llvm/IR/DebugLoc.h"
41#include "llvm/MC/MCInstrDesc.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000042#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000044#include "llvm/Support/Compiler.h"
Evan Cheng10043e22007-01-19 07:51:42 +000045#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000046#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000047#include "llvm/Support/Format.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000049#include "llvm/Support/raw_ostream.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000050#include <algorithm>
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000051#include <cassert>
52#include <cstdint>
53#include <iterator>
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000054#include <utility>
55#include <vector>
56
Evan Cheng10043e22007-01-19 07:51:42 +000057using namespace llvm;
58
Chandler Carruth84e68b22014-04-22 02:41:26 +000059#define DEBUG_TYPE "arm-cp-islands"
60
James Molloy9b3b8992017-02-13 14:07:25 +000061#define ARM_CP_ISLANDS_OPT_NAME \
62 "ARM constant island placement and branch shortening pass"
Evan Chengdb73d682009-08-14 00:32:16 +000063STATISTIC(NumCPEs, "Number of constpool entries");
64STATISTIC(NumSplit, "Number of uncond branches inserted");
65STATISTIC(NumCBrFixed, "Number of cond branches fixed");
66STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
67STATISTIC(NumTBs, "Number of table branches generated");
68STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000069STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000070STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000071STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000072STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000073
Jim Grosbach8d92ec42009-11-11 02:47:19 +000074static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000075AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000076 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000077
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000078static cl::opt<unsigned>
79CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
80 cl::desc("The max number of iteration for converge"));
81
James Molloy70a3d6d2016-11-01 13:37:41 +000082static cl::opt<bool> SynthesizeThumb1TBB(
83 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
84 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
85 "equivalent to the TBB/TBH instructions"));
86
Evan Cheng10043e22007-01-19 07:51:42 +000087namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000088
Dale Johannesene18b13b2007-02-23 05:02:36 +000089 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000090 /// requires constant pool entries to be scattered among the instructions
91 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000092 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000093 /// special instructions.
94 ///
95 /// The terminology used in this pass includes:
96 /// Islands - Clumps of constants placed in the function.
97 /// Water - Potential places where an island could be formed.
98 /// CPE - A constant pool entry that has been placed somewhere, which
99 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000100 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000101 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000102
Evan Cheng10043e22007-01-19 07:51:42 +0000103 /// WaterList - A sorted list of basic blocks where islands could be placed
104 /// (i.e. blocks that don't fall through to the following block, due
105 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000106 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000107
Bob Wilson2f9be502009-10-15 20:49:47 +0000108 /// NewWaterList - The subset of WaterList that was created since the
109 /// previous iteration by inserting unconditional branches.
110 SmallSet<MachineBasicBlock*, 4> NewWaterList;
111
Eugene Zelenko076468c2017-09-20 21:35:51 +0000112 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000113
Evan Cheng10043e22007-01-19 07:51:42 +0000114 /// CPUser - One user of a constant pool, keeping the machine instruction
115 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000116 /// allowed from the instruction to the CP. The HighWaterMark records the
117 /// highest basic block where a new CPEntry can be placed. To ensure this
118 /// pass terminates, the CP entries are initially placed at the end of the
119 /// function and then move monotonically to lower addresses. The
120 /// exception to this rule is when the current CP entry for a particular
121 /// CPUser is out of range, but there is another CP entry for the same
122 /// constant value in range. We want to use the existing in-range CP
123 /// entry, but if it later moves out of range, the search for new water
124 /// should resume where it left off. The HighWaterMark is used to record
125 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000126 struct CPUser {
127 MachineInstr *MI;
128 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000129 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000130 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000131 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000132 bool IsSoImm;
Eugene Zelenko076468c2017-09-20 21:35:51 +0000133 bool KnownAlignment = false;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000134
Evan Chengd2919a12009-07-23 18:27:47 +0000135 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
136 bool neg, bool soimm)
Eugene Zelenko076468c2017-09-20 21:35:51 +0000137 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000138 HighWaterMark = CPEMI->getParent();
139 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000140
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000141 /// getMaxDisp - Returns the maximum displacement supported by MI.
142 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000143 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000144 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000145 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000146 }
Evan Cheng10043e22007-01-19 07:51:42 +0000147 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000148
Evan Cheng10043e22007-01-19 07:51:42 +0000149 /// CPUsers - Keep track of all of the machine instructions that use various
150 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000151 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000152
Evan Cheng8b7700f2007-02-09 20:54:44 +0000153 /// CPEntry - One per constant pool entry, keeping the machine instruction
154 /// pointer, the constpool index, and the number of CPUser's which
155 /// reference this entry.
156 struct CPEntry {
157 MachineInstr *CPEMI;
158 unsigned CPI;
159 unsigned RefCount;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000160
Evan Cheng8b7700f2007-02-09 20:54:44 +0000161 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
162 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
163 };
164
165 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000166 /// instructions. For each original constpool index (i.e. those that existed
167 /// upon entry to this pass), it keeps a vector of entries. Original
168 /// elements are cloned as we go along; the clones are put in the vector of
169 /// the original element, but have distinct CPIs.
170 ///
171 /// The first half of CPEntries contains generic constants, the second half
172 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
173 /// which vector it will be in here.
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000174 std::vector<std::vector<CPEntry>> CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000175
Tim Northovera603c402015-05-31 19:22:07 +0000176 /// Maps a JT index to the offset in CPEntries containing copies of that
177 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
178 DenseMap<int, int> JumpTableEntryIndices;
179
180 /// Maps a JT index to the LEA that actually uses the index to calculate its
181 /// base address.
182 DenseMap<int, int> JumpTableUserIndices;
183
Evan Cheng22c7cf52007-01-25 03:12:46 +0000184 /// ImmBranch - One per immediate branch, keeping the machine instruction
185 /// pointer, conditional or unconditional, the max displacement,
186 /// and (if isCond is true) the corresponding unconditional branch
187 /// opcode.
188 struct ImmBranch {
189 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000190 unsigned MaxDisp : 31;
191 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000192 unsigned UncondBr;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000193
Matthias Braunfa3872e2015-05-18 20:27:55 +0000194 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000195 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000196 };
197
Evan Chengc95f95b2007-05-16 05:14:06 +0000198 /// ImmBranches - Keep track of all the immediate branch instructions.
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.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000202 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000203
Evan Chengc6d70ae2009-07-29 02:18:14 +0000204 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
205 SmallVector<MachineInstr*, 4> T2JumpTables;
206
Evan Cheng7fa69642007-01-30 01:18:38 +0000207 /// HasFarJump - True if any far jump instruction has been emitted during
208 /// the branch fix up pass.
209 bool HasFarJump;
210
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000211 MachineFunction *MF;
212 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000213 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000214 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000215 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000216 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000217 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000218 bool isThumb2;
James Molloy70a3d6d2016-11-01 13:37:41 +0000219 bool isPositionIndependentOrROPI;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000220
Evan Cheng10043e22007-01-19 07:51:42 +0000221 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000222 static char ID;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000223
Owen Andersona7aed182010-08-06 18:33:48 +0000224 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000225
Craig Topper6bc27bf2014-03-10 02:09:33 +0000226 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000227
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000228 MachineFunctionProperties getRequiredProperties() const override {
229 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000230 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000231 }
232
Mehdi Amini117296c2016-10-01 02:56:57 +0000233 StringRef getPassName() const override {
James Molloy9b3b8992017-02-13 14:07:25 +0000234 return ARM_CP_ISLANDS_OPT_NAME;
Evan Cheng10043e22007-01-19 07:51:42 +0000235 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000236
Evan Cheng10043e22007-01-19 07:51:42 +0000237 private:
Tim Northovera603c402015-05-31 19:22:07 +0000238 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
239 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000240 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000241 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000242 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000243 void scanFunctionJumpTables();
244 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
245 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
246 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
247 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
248 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000249 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000250 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
251 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000252 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000253 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000254 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000255 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000256 void removeDeadCPEMI(MachineInstr *CPEMI);
257 bool removeUnusedCPEntries();
258 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
259 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
260 bool DoDump = false);
261 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000262 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000263 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
264 bool fixupImmediateBr(ImmBranch &Br);
265 bool fixupConditionalBr(ImmBranch &Br);
266 bool fixupUnconditionalBr(ImmBranch &Br);
267 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000268 bool optimizeThumb2Instructions();
269 bool optimizeThumb2Branches();
270 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000271 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
272 unsigned &DeadSize, bool &CanDeleteLEA,
273 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000274 bool optimizeThumb2JumpTables();
275 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000276 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000277
Jim Grosbach190e7b62012-03-23 23:07:03 +0000278 unsigned getOffsetOf(MachineInstr *MI) const;
279 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000280 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000281 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000282
Jim Grosbach190e7b62012-03-23 23:07:03 +0000283 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000284 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000285 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000286 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000287 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000288 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000289 }
Evan Cheng10043e22007-01-19 07:51:42 +0000290 };
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000291
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000292} // end anonymous namespace
Evan Cheng10043e22007-01-19 07:51:42 +0000293
Eugene Zelenko076468c2017-09-20 21:35:51 +0000294char ARMConstantIslands::ID = 0;
295
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000296/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000297void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000298#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000299 assert(std::is_sorted(MF->begin(), MF->end(),
300 [this](const MachineBasicBlock &LHS,
301 const MachineBasicBlock &RHS) {
302 return BBInfo[LHS.getNumber()].postOffset() <
303 BBInfo[RHS.getNumber()].postOffset();
304 }));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000305 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000306 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
307 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000308 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000309 // Verify offset using the real max displacement without the safety
310 // adjustment.
311 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000312 /* DoDump = */ true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000313 LLVM_DEBUG(dbgs() << "OK\n");
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000314 continue;
315 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000316 LLVM_DEBUG(dbgs() << "Out of range.\n");
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000317 dumpBBs();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000318 LLVM_DEBUG(MF->dump());
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000319 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000320 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000321#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000322}
323
Aaron Ballman615eb472017-10-15 14:32:27 +0000324#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000325/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000326LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000327 LLVM_DEBUG({
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000328 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
329 const BasicBlockInfo &BBI = BBInfo[J];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000330 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000331 << " kb=" << unsigned(BBI.KnownBits)
332 << " ua=" << unsigned(BBI.Unalign)
333 << " pa=" << unsigned(BBI.PostAlign)
334 << format(" size=%#x\n", BBInfo[J].Size);
335 }
336 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000337}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000338#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000339
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000340bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
341 MF = &mf;
342 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000343
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000344 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
345 << MCP->getConstants().size() << " CP entries, aligned to "
346 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000347
Eric Christopher1b21f002015-01-29 00:19:33 +0000348 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
349 TII = STI->getInstrInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +0000350 isPositionIndependentOrROPI =
351 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000352 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000353
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000354 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000355 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000356 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000357
358 HasFarJump = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000359 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
Evan Cheng7fa69642007-01-30 01:18:38 +0000360
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000361 // This pass invalidates liveness information when it splits basic blocks.
362 MF->getRegInfo().invalidateLiveness();
363
Evan Cheng10043e22007-01-19 07:51:42 +0000364 // Renumber all of the machine basic blocks in the function, guaranteeing that
365 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000366 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000367
Jim Grosbach5d577142009-11-12 17:25:07 +0000368 // Try to reorder and otherwise adjust the block layout to make good use
369 // of the TB[BH] instructions.
370 bool MadeChange = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000371 if (GenerateTBB && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000372 scanFunctionJumpTables();
373 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000374 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000375 T2JumpTables.clear();
376 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000377 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000378 }
379
Evan Cheng10043e22007-01-19 07:51:42 +0000380 // Perform the initial placement of the constant pool entries. To start with,
381 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000382 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000383 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000384 doInitialConstPlacement(CPEMIs);
385
386 if (MF->getJumpTableInfo())
387 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000388
Evan Cheng10043e22007-01-19 07:51:42 +0000389 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000390 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000391
Evan Cheng10043e22007-01-19 07:51:42 +0000392 // Do the initial scan of the function, building up information about the
393 // sizes of each block, the location of all the water, and finding all of the
394 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000395 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000396 CPEMIs.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000397 LLVM_DEBUG(dumpBBs());
Dale Johannesenc17dd572010-07-23 22:50:23 +0000398
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000399 // Functions with jump tables need an alignment of 4 because they use the ADR
400 // instruction, which aligns the PC to 4 bytes before adding an offset.
401 if (!T2JumpTables.empty())
402 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000403
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000404 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000405 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000406
Evan Cheng7fa69642007-01-30 01:18:38 +0000407 // Iteratively place constant pool entries and fix up branches until there
408 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000409 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000410 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000411 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000412 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000413 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000414 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000415 // If it doesn't end in 10, the input may have huge BB or many CPEs.
416 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000417 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
418 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000419 report_fatal_error("Constant Island pass failed to converge!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000420 LLVM_DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000421
Bob Wilson2f9be502009-10-15 20:49:47 +0000422 // Clear NewWaterList now. If we split a block for branches, it should
423 // appear as "new water" for the next iteration of constant pool placement.
424 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000425
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000426 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000427 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000428 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000429 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000430 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000431 report_fatal_error("Branch Fix Up pass failed to converge!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000433
434 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000435 break;
436 MadeChange = true;
437 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000438
Bradley Smitha1189102016-01-15 10:26:17 +0000439 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000440 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000441 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000442
Bradley Smitha1189102016-01-15 10:26:17 +0000443 // Shrink 32-bit branch instructions.
444 if (isThumb && STI->hasV8MBaselineOps())
445 MadeChange |= optimizeThumb2Branches();
446
447 // Optimize jump tables using TBB / TBH.
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000448 if (GenerateTBB && !STI->genExecuteOnly())
Bradley Smitha1189102016-01-15 10:26:17 +0000449 MadeChange |= optimizeThumb2JumpTables();
450
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000451 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000452 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000453
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000454 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
455 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000456 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000457 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000458
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000459 // Save the mapping between original and cloned constpool entries.
460 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
461 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
462 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000463 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
464 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000465 }
466 }
467
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000469
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000470 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000471 WaterList.clear();
472 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000473 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000474 JumpTableEntryIndices.clear();
475 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000476 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000477 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000478 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000479
480 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000481}
482
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000483/// Perform the initial placement of the regular constant pool entries.
Tim Northovera603c402015-05-31 19:22:07 +0000484/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000485void
Tim Northovera603c402015-05-31 19:22:07 +0000486ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000487 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000488 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
489 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000490
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000491 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000492 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000493
494 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000495 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000496
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000497 // The function needs to be as aligned as the basic blocks. The linker may
498 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000499 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000500
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000501 // Order the entries in BB by descending alignment. That ensures correct
502 // alignment of all entries as long as BB is sufficiently aligned. Keep
503 // track of the insertion point for each alignment. We are going to bucket
504 // sort the entries as they are created.
505 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000506
Evan Cheng10043e22007-01-19 07:51:42 +0000507 // Add all of the constants from the constant pool to the end block, use an
508 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000509 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000510
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000511 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000512 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000513 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000514 unsigned Align = CPs[i].getAlignment();
515 assert(isPowerOf2_32(Align) && "Invalid alignment");
516 // Verify that all constant pool entries are a multiple of their alignment.
517 // If not, we would have to pad them out so that instructions stay aligned.
518 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
519
520 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
521 unsigned LogAlign = Log2_32(Align);
522 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000523 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000524 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000525 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000526 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000527
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000528 // Ensure that future entries with higher alignment get inserted before
529 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000530 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000531 if (InsPoint[a] == InsAt)
532 InsPoint[a] = CPEMI;
533
Evan Cheng8b7700f2007-02-09 20:54:44 +0000534 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000535 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000536 ++NumCPEs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000537 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
538 << Size << ", align = " << Align << '\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000539 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000540 LLVM_DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000541}
542
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000543/// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
Tim Northovera603c402015-05-31 19:22:07 +0000544/// instructions can be made more efficient if the jump table immediately
545/// follows the instruction, it's best to place them immediately next to their
546/// jumps to begin with. In almost all cases they'll never be moved from that
547/// position.
548void ARMConstantIslands::doInitialJumpTablePlacement(
549 std::vector<MachineInstr *> &CPEMIs) {
550 unsigned i = CPEntries.size();
551 auto MJTI = MF->getJumpTableInfo();
552 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
553
554 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
555 for (MachineBasicBlock &MBB : *MF) {
556 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000557 if (MI == MBB.end())
558 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000559
560 unsigned JTOpcode;
561 switch (MI->getOpcode()) {
562 default:
563 continue;
564 case ARM::BR_JTadd:
565 case ARM::BR_JTr:
566 case ARM::tBR_JTr:
Momchil Velikov4a91fb92017-11-15 12:02:55 +0000567 case ARM::BR_JTm_i12:
568 case ARM::BR_JTm_rs:
Tim Northovera603c402015-05-31 19:22:07 +0000569 JTOpcode = ARM::JUMPTABLE_ADDRS;
570 break;
571 case ARM::t2BR_JT:
572 JTOpcode = ARM::JUMPTABLE_INSTS;
573 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000574 case ARM::tTBB_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000575 case ARM::t2TBB_JT:
576 JTOpcode = ARM::JUMPTABLE_TBB;
577 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000578 case ARM::tTBH_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000579 case ARM::t2TBH_JT:
580 JTOpcode = ARM::JUMPTABLE_TBH;
581 break;
582 }
583
584 unsigned NumOps = MI->getDesc().getNumOperands();
585 MachineOperand JTOp =
586 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
587 unsigned JTI = JTOp.getIndex();
588 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
589 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
590 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
591 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
592 DebugLoc(), TII->get(JTOpcode))
593 .addImm(i++)
594 .addJumpTableIndex(JTI)
595 .addImm(Size);
596 CPEMIs.push_back(CPEMI);
597 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
598 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
599 if (!LastCorrectlyNumberedBB)
600 LastCorrectlyNumberedBB = &MBB;
601 }
602
603 // If we did anything then we need to renumber the subsequent blocks.
604 if (LastCorrectlyNumberedBB)
605 MF->RenumberBlocks(LastCorrectlyNumberedBB);
606}
607
Dale Johannesene18b13b2007-02-23 05:02:36 +0000608/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000609/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000610bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000611 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000612 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000613 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000614 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000615 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000616
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000617 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000618 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000619 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000620
Tim Northoverab85dcc2014-11-13 17:58:51 +0000621 // Try to analyze the end of the block. A potential fallthrough may already
622 // have an unconditional branch for whatever reason.
623 MachineBasicBlock *TBB, *FBB;
624 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000625 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000626 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000627}
628
Evan Cheng8b7700f2007-02-09 20:54:44 +0000629/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
630/// look up the corresponding CPEntry.
Eugene Zelenko076468c2017-09-20 21:35:51 +0000631ARMConstantIslands::CPEntry *
632ARMConstantIslands::findConstPoolEntry(unsigned CPI,
633 const MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +0000634 std::vector<CPEntry> &CPEs = CPEntries[CPI];
635 // Number of entries per constpool index should be small, just do a
636 // linear search.
637 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
638 if (CPEs[i].CPEMI == CPEMI)
639 return &CPEs[i];
640 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000641 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000642}
643
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000644/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000645/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000646unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000647 switch (CPEMI->getOpcode()) {
648 case ARM::CONSTPOOL_ENTRY:
649 break;
650 case ARM::JUMPTABLE_TBB:
James Molloy70a3d6d2016-11-01 13:37:41 +0000651 return isThumb1 ? 2 : 0;
Tim Northovera603c402015-05-31 19:22:07 +0000652 case ARM::JUMPTABLE_TBH:
James Molloy70a3d6d2016-11-01 13:37:41 +0000653 return isThumb1 ? 2 : 1;
Tim Northovera603c402015-05-31 19:22:07 +0000654 case ARM::JUMPTABLE_INSTS:
655 return 1;
656 case ARM::JUMPTABLE_ADDRS:
657 return 2;
658 default:
659 llvm_unreachable("unknown constpool entry kind");
660 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000661
Tim Northovera603c402015-05-31 19:22:07 +0000662 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000663 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
664 unsigned Align = MCP->getConstants()[CPI].getAlignment();
665 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
666 return Log2_32(Align);
667}
668
Jim Grosbach190e7b62012-03-23 23:07:03 +0000669/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000670/// information about the sizes of each block and the locations of all
671/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000672void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000673 for (MachineBasicBlock &MBB : *MF) {
674 for (MachineInstr &I : MBB)
James Molloy70a3d6d2016-11-01 13:37:41 +0000675 if (I.isBranch() &&
676 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000677 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000678 }
679}
680
Jim Grosbach190e7b62012-03-23 23:07:03 +0000681/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000682/// information about the sizes of each block, the location of all the water,
683/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000684void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000685initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000686
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000687 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000688
689 // The known bits of the entry block offset are determined by the function
690 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000691 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000692
693 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000694 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000695
Bill Wendling18581a42010-12-21 01:54:40 +0000696 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000697 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000698 // If this block doesn't fall through into the next MBB, then this is
699 // 'water' that a constant pool island could be placed.
700 if (!BBHasFallthrough(&MBB))
701 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000702
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000703 for (MachineInstr &I : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000704 if (I.isDebugInstr())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000705 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000706
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000707 unsigned Opc = I.getOpcode();
708 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000709 bool isCond = false;
710 unsigned Bits = 0;
711 unsigned Scale = 1;
712 int UOpc = Opc;
713 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000714 default:
715 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000716 case ARM::t2BR_JT:
James Molloy70a3d6d2016-11-01 13:37:41 +0000717 case ARM::tBR_JTr:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000718 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000719 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000720 case ARM::Bcc:
721 isCond = true;
722 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000723 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000724 case ARM::B:
725 Bits = 24;
726 Scale = 4;
727 break;
728 case ARM::tBcc:
729 isCond = true;
730 UOpc = ARM::tB;
731 Bits = 8;
732 Scale = 2;
733 break;
734 case ARM::tB:
735 Bits = 11;
736 Scale = 2;
737 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000738 case ARM::t2Bcc:
739 isCond = true;
740 UOpc = ARM::t2B;
741 Bits = 20;
742 Scale = 2;
743 break;
744 case ARM::t2B:
745 Bits = 24;
746 Scale = 2;
747 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000748 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000749
750 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000751 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000752 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000753 }
754
Evan Cheng7fa69642007-01-30 01:18:38 +0000755 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000756 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000757
Tim Northovera603c402015-05-31 19:22:07 +0000758 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
759 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
760 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000761 continue;
762
Evan Cheng10043e22007-01-19 07:51:42 +0000763 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000764 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
765 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000766 // We found one. The addressing mode tells us the max displacement
767 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000768
Evan Cheng10043e22007-01-19 07:51:42 +0000769 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000770 unsigned Bits = 0;
771 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000772 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000773 bool IsSoImm = false;
774
775 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000776 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000777 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000778
779 // Taking the address of a CP entry.
780 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000781 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000782 // This takes a SoImm, which is 8 bit immediate rotated. We'll
783 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000784 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000785 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000786 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000787 Scale = 4;
788 NegOk = true;
789 IsSoImm = true;
790 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000791 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000792 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000793 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000794 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000795 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000796 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000797 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000798 Bits = 8;
799 Scale = 4;
800 break;
801
David Majnemer452f1f92013-06-04 17:46:15 +0000802 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000803 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000804 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000805 case ARM::t2LDRpci:
James Molloy9abb2fa2016-09-26 07:26:24 +0000806 case ARM::t2LDRHpci:
Kristof Beyls5ac6adb2017-02-23 12:24:55 +0000807 case ARM::t2LDRBpci:
Evan Chengfd522992007-02-01 20:44:52 +0000808 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000809 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000810 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000811
812 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000813 Bits = 8;
814 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000815 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000816
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000817 case ARM::VLDRD:
818 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000819 Bits = 8;
820 Scale = 4; // +-(offset_8*4)
821 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000822 break;
Sjoerd Meijerf4a7fa72018-02-13 15:34:09 +0000823 case ARM::VLDRH:
824 Bits = 8;
825 Scale = 2; // +-(offset_8*2)
826 NegOk = true;
827 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000828
829 case ARM::tLDRHi:
830 Bits = 5;
831 Scale = 2; // +(offset_5*2)
832 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000833 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000834
Evan Cheng10043e22007-01-19 07:51:42 +0000835 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000836 unsigned CPI = I.getOperand(op).getIndex();
837 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000838 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
839 CPI = JumpTableEntryIndices[CPI];
840 }
841
Evan Cheng8b7700f2007-02-09 20:54:44 +0000842 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000843 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000844 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000845
846 // Increment corresponding CPEntry reference count.
847 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
848 assert(CPE && "Cannot find a corresponding CPEntry!");
849 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000850
Evan Cheng10043e22007-01-19 07:51:42 +0000851 // Instructions can only use one CP entry, don't bother scanning the
852 // rest of the operands.
853 break;
854 }
855 }
Evan Cheng10043e22007-01-19 07:51:42 +0000856 }
857}
858
Jim Grosbach190e7b62012-03-23 23:07:03 +0000859/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000860/// from the start of the function. This offset changes as stuff is moved
861/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000862unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000863 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000864
Evan Cheng10043e22007-01-19 07:51:42 +0000865 // The offset is composed of two things: the sum of the sizes of all MBB's
866 // before this instruction's block, and the offset from the start of the block
867 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000868 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000869
870 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000871 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000872 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000873 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000874 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000875 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000876}
877
878/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
879/// ID.
880static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
881 const MachineBasicBlock *RHS) {
882 return LHS->getNumber() < RHS->getNumber();
883}
884
Jim Grosbach190e7b62012-03-23 23:07:03 +0000885/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000886/// machine function, it upsets all of the block numbers. Renumber the blocks
887/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000888void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000889 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000890 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000891
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000892 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000893 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000894 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000895
896 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000897 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000898 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000899 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
900 CompareMBBNumbers);
901 WaterList.insert(IP, NewBB);
902}
903
Evan Cheng10043e22007-01-19 07:51:42 +0000904/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000905/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000906/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000907MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000908 MachineBasicBlock *OrigBB = MI->getParent();
909
910 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000911 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000912 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000913 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000914 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000915
Evan Cheng10043e22007-01-19 07:51:42 +0000916 // Splice the instructions starting with MI over to NewBB.
917 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000918
Evan Cheng10043e22007-01-19 07:51:42 +0000919 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000920 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000921 // There doesn't seem to be meaningful DebugInfo available; this doesn't
922 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000923 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000924 if (!isThumb)
925 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
926 else
Diana Picusbd66b7d2017-01-20 08:15:24 +0000927 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
928 .addMBB(NewBB)
929 .add(predOps(ARMCC::AL));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000930 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000931
Evan Cheng10043e22007-01-19 07:51:42 +0000932 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000933 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000934
Evan Cheng10043e22007-01-19 07:51:42 +0000935 // OrigBB branches to NewBB.
936 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000937
Evan Cheng10043e22007-01-19 07:51:42 +0000938 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000939 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000940 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000941 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000942
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000943 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000944 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000945 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000946
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000947 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000948 // available water after it (but not if it's already there, which happens
949 // when splitting before a conditional branch that is followed by an
950 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000951 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000952 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
953 CompareMBBNumbers);
954 MachineBasicBlock* WaterBB = *IP;
955 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000956 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000957 else
958 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000959 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000960
Dale Johannesenc17dd572010-07-23 22:50:23 +0000961 // Figure out how large the OrigBB is. As the first half of the original
962 // block, it cannot contain a tablejump. The size includes
963 // the new jump we added. (It should be possible to do this without
964 // recounting everything, but it's very confusing, and this is rarely
965 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000966 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000967
Dale Johannesenc17dd572010-07-23 22:50:23 +0000968 // Figure out how large the NewMBB is. As the second half of the original
969 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000970 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000971
Dale Johannesen01ee5752007-02-25 00:47:03 +0000972 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000973 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000974
975 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000976}
977
Jim Grosbach190e7b62012-03-23 23:07:03 +0000978/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000979/// displacement computation. Update U.KnownAlignment to match its current
980/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000981unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
982 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000983 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
984 unsigned KnownBits = BBI.internalKnownBits();
985
986 // The value read from PC is offset from the actual instruction address.
987 UserOffset += (isThumb ? 4 : 8);
988
989 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
990 // Make sure U.getMaxDisp() returns a constrained range.
991 U.KnownAlignment = (KnownBits >= 2);
992
993 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
994 // purposes of the displacement computation; compensate for that here.
995 // For unknown alignments, getMaxDisp() constrains the range instead.
996 if (isThumb && U.KnownAlignment)
997 UserOffset &= ~3u;
998
999 return UserOffset;
1000}
1001
Jim Grosbach190e7b62012-03-23 23:07:03 +00001002/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001003/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001004/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001005/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001006/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1007/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001008bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001009 unsigned TrialOffset, unsigned MaxDisp,
1010 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001011 if (UserOffset <= TrialOffset) {
1012 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001013 if (TrialOffset - UserOffset <= 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 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001017 if (UserOffset - TrialOffset <= MaxDisp)
1018 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001019 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001020 }
1021 return false;
1022}
1023
Jim Grosbach190e7b62012-03-23 23:07:03 +00001024/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001025/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001026///
1027/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001028bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001029 MachineBasicBlock* Water, CPUser &U,
1030 unsigned &Growth) {
1031 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1032 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1033 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001034 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001035 if (++NextBlock == MF->end()) {
1036 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1037 NextBlockAlignment = 0;
1038 } else {
1039 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1040 NextBlockAlignment = NextBlock->getAlignment();
1041 }
1042 unsigned Size = U.CPEMI->getOperand(2).getImm();
1043 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001044
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001045 // The CPE may be able to hide in the alignment padding before the next
1046 // block. It may also cause more padding to be required if it is more aligned
1047 // that the next block.
1048 if (CPEEnd > NextBlockOffset) {
1049 Growth = CPEEnd - NextBlockOffset;
1050 // Compute the padding that would go at the end of the CPE to align the next
1051 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001052 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001053
1054 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001055 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001056 // in blocks between CPE and the user.
1057 if (CPEOffset < UserOffset)
1058 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1059 } else
1060 // CPE fits in existing padding.
1061 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001062
Jim Grosbach190e7b62012-03-23 23:07:03 +00001063 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001064}
1065
Jim Grosbach190e7b62012-03-23 23:07:03 +00001066/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001067/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001068bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001069 MachineInstr *CPEMI, unsigned MaxDisp,
1070 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001071 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001072
Dale Johannesene18b13b2007-02-23 05:02:36 +00001073 if (DoDump) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001074 LLVM_DEBUG({
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001075 unsigned Block = MI->getParent()->getNumber();
1076 const BasicBlockInfo &BBI = BBInfo[Block];
1077 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1078 << " max delta=" << MaxDisp
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001079 << format(" insn address=%#x", UserOffset) << " in "
1080 << printMBBReference(*MI->getParent()) << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001081 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1082 << format("CPE address=%#x offset=%+d: ", CPEOffset,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001083 int(CPEOffset - UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001084 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001085 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001086
Jim Grosbach190e7b62012-03-23 23:07:03 +00001087 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001088}
1089
Evan Chenge4510972009-01-28 00:53:34 +00001090#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001091/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1092/// unconditionally branches to its only successor.
1093static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1094 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1095 return false;
1096
1097 MachineBasicBlock *Succ = *MBB->succ_begin();
1098 MachineBasicBlock *Pred = *MBB->pred_begin();
1099 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001100 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1101 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001102 return PredMI->getOperand(0).getMBB() == Succ;
1103 return false;
1104}
Evan Chenge4510972009-01-28 00:53:34 +00001105#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001106
Jim Grosbach190e7b62012-03-23 23:07:03 +00001107void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001108 unsigned BBNum = BB->getNumber();
1109 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001110 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001111 // Include the alignment of the current block.
1112 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1113 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1114 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001115
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001116 // This is where block i begins. Stop if the offset is already correct,
1117 // and we have updated 2 blocks. This is the maximum number of blocks
1118 // changed before calling this function.
1119 if (i > BBNum + 2 &&
1120 BBInfo[i].Offset == Offset &&
1121 BBInfo[i].KnownBits == KnownBits)
1122 break;
1123
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001124 BBInfo[i].Offset = Offset;
1125 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001126 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001127}
1128
Jim Grosbach190e7b62012-03-23 23:07:03 +00001129/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001130/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001131/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001132/// the entry, false if we didn't.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001133bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1134 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001135 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001136 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1137 assert(CPE && "Unexpected!");
1138 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001139 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001140 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001141 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001142 return true;
1143 }
1144 return false;
1145}
1146
Tim Northovera603c402015-05-31 19:22:07 +00001147unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1148 if (CPEMI->getOperand(1).isCPI())
1149 return CPEMI->getOperand(1).getIndex();
1150
1151 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1152}
1153
Dale Johannesene18b13b2007-02-23 05:02:36 +00001154/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1155/// if not, see if an in-range clone of the CPE is in range, and if so,
1156/// change the data structures so the user references the clone. Returns:
1157/// 0 = no existing entry found
1158/// 1 = entry found, and there were no code insertions or deletions
1159/// 2 = entry found, and there were code insertions or deletions
Eugene Zelenko076468c2017-09-20 21:35:51 +00001160int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001161 MachineInstr *UserMI = U.MI;
1162 MachineInstr *CPEMI = U.CPEMI;
1163
1164 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001165 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1166 true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001167 LLVM_DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001168 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001169 }
1170
Dale Johannesene18b13b2007-02-23 05:02:36 +00001171 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001172 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001173 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1174 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1175 // We already tried this one
1176 if (CPEs[i].CPEMI == CPEMI)
1177 continue;
1178 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001179 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001180 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001181 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001182 U.NegOk)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001183 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1184 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001185 // Point the CPUser node to the replacement
1186 U.CPEMI = CPEs[i].CPEMI;
1187 // Change the CPI in the instruction operand to refer to the clone.
1188 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001189 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001190 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001191 break;
1192 }
1193 // Adjust the refcount of the clone...
1194 CPEs[i].RefCount++;
1195 // ...and the original. If we didn't remove the old entry, none of the
1196 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001197 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001198 }
1199 }
1200 return 0;
1201}
1202
Dale Johannesen440995b2007-02-28 18:41:23 +00001203/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1204/// the specific unconditional branch instruction.
1205static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001206 switch (Opc) {
1207 case ARM::tB:
1208 return ((1<<10)-1)*2;
1209 case ARM::t2B:
1210 return ((1<<23)-1)*2;
1211 default:
1212 break;
1213 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001214
David Goodwin27303cd2009-06-30 18:04:13 +00001215 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001216}
1217
Jim Grosbach190e7b62012-03-23 23:07:03 +00001218/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001219/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001220/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001221/// is set to the WaterList entry. For Thumb, prefer water that will not
1222/// introduce padding to water that will. To ensure that this pass
1223/// terminates, the CPE location for a particular CPUser is only allowed to
1224/// move to a lower address, so search backward from the end of the list and
1225/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001226bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001227 water_iterator &WaterIter,
1228 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001229 if (WaterList.empty())
1230 return false;
1231
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001232 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001233 // The nearest water without splitting the UserBB is right after it.
1234 // If the distance is still large (we have a big BB), then we need to split it
1235 // if we don't converge after certain iterations. This helps the following
1236 // situation to converge:
1237 // BB0:
1238 // Big BB
1239 // BB1:
1240 // Constant Pool
1241 // When a CP access is out of range, BB0 may be used as water. However,
1242 // inserting islands between BB0 and BB1 makes other accesses out of range.
1243 MachineBasicBlock *UserBB = U.MI->getParent();
1244 unsigned MinNoSplitDisp =
1245 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1246 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1247 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001248 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001249 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001250 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001251 // Check if water is in range and is either at a lower address than the
1252 // current "high water mark" or a new water block that was created since
1253 // the previous iteration by inserting an unconditional branch. In the
1254 // latter case, we want to allow resetting the high water mark back to
1255 // this new water since we haven't seen it before. Inserting branches
1256 // should be relatively uncommon and when it does happen, we want to be
1257 // sure to take advantage of it for all the CPEs near that block, so that
1258 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001259 // When CloserWater is true, we try to find the lowest address after (or
1260 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001261 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001262 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001263 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001264 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1265 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001266 // This is the least amount of required padding seen so far.
1267 BestGrowth = Growth;
1268 WaterIter = IP;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001269 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1270 << " Growth=" << Growth << '\n');
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001271
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001272 if (CloserWater && WaterBB == U.MI->getParent())
1273 return true;
1274 // Keep looking unless it is perfect and we're not looking for the lowest
1275 // possible address.
1276 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001277 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001278 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001279 if (IP == B)
1280 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001281 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001282 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001283}
1284
Jim Grosbach190e7b62012-03-23 23:07:03 +00001285/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001286/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1287/// block is used if in range, and the conditional branch munged so control
1288/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001289/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001290/// block following which the new island can be inserted (the WaterList
1291/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001292void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001293 unsigned UserOffset,
1294 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001295 CPUser &U = CPUsers[CPUserIndex];
1296 MachineInstr *UserMI = U.MI;
1297 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001298 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001299 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001300 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001301
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001302 // If the block does not end in an unconditional branch already, and if the
1303 // end of the block is within range, make new water there. (The addition
1304 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001305 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001306 if (BBHasFallthrough(UserMBB)) {
1307 // Size of branch to insert.
1308 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001309 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001310 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001311
Jim Grosbach190e7b62012-03-23 23:07:03 +00001312 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001313 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1314 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001315 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001316 // Add an unconditional branch from UserMBB to fallthrough block. Record
1317 // it for branch lengthening; this new branch will not get out of range,
1318 // but if the preceding conditional branch is out of range, the targets
1319 // will be exchanged, and the altered branch may be out of range, so the
1320 // machinery has to know about it.
1321 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1322 if (!isThumb)
1323 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1324 else
Diana Picusbd66b7d2017-01-20 08:15:24 +00001325 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1326 .addMBB(NewMBB)
1327 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001328 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1329 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1330 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001331 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001332 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001333 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001334 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001335 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001336
1337 // What a big block. Find a place within the block to split it. This is a
1338 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1339 // entries are 4 bytes: if instruction I references island CPE, and
1340 // instruction I+1 references CPE', it will not work well to put CPE as far
1341 // forward as possible, since then CPE' cannot immediately follow it (that
1342 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1343 // need to create a new island. So, we make a first guess, then walk through
1344 // the instructions between the one currently being looked at and the
1345 // possible insertion point, and make sure any other instructions that
1346 // reference CPEs will be able to use the same island area; if not, we back
1347 // up the insertion point.
1348
1349 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001350 // point where we can add a 4-byte branch instruction, and then align to
1351 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001352 unsigned LogAlign = MF->getAlignment();
1353 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1354 unsigned KnownBits = UserBBI.internalKnownBits();
1355 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001356 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001357 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1358 BaseInsertOffset));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001359
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001360 // The 4 in the following is for the unconditional branch we'll be inserting
1361 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001362 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001363 BaseInsertOffset -= 4;
1364
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001365 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1366 << " la=" << LogAlign << " kb=" << KnownBits
1367 << " up=" << UPad << '\n');
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001368
1369 // This could point off the end of the block if we've already got constant
1370 // pool entries following this block; only the last one is in the water list.
1371 // Back past any possible branches (allow for a conditional and a maximally
1372 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001373 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001374 // Ensure BaseInsertOffset is larger than the offset of the instruction
1375 // following UserMI so that the loop which searches for the split point
1376 // iterates at least once.
1377 BaseInsertOffset =
1378 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001379 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001380 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001381 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001382 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001383 CPEMI->getOperand(2).getImm();
1384 MachineBasicBlock::iterator MI = UserMI;
1385 ++MI;
1386 unsigned CPUIndex = CPUserIndex+1;
1387 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001388 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001389 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001390 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001391 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001392 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001393 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001394 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001395 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001396 // Shift intertion point by one unit of alignment so it is within reach.
1397 BaseInsertOffset -= 1u << LogAlign;
1398 EndInsertOffset -= 1u << LogAlign;
1399 }
1400 // This is overly conservative, as we don't account for CPEMIs being
1401 // reused within the block, but it doesn't matter much. Also assume CPEs
1402 // are added in order with alignment padding. We may eventually be able
1403 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001404 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001405 CPUIndex++;
1406 }
1407
1408 // Remember the last IT instruction.
1409 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001410 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001411 }
1412
1413 --MI;
1414
1415 // Avoid splitting an IT block.
1416 if (LastIT) {
1417 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001418 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001419 if (CC != ARMCC::AL)
1420 MI = LastIT;
1421 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001422
Martin Storsjo5ab1d102018-08-22 20:34:12 +00001423 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1424 // On Windows, this instruction pair is covered by one single
1425 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1426 // constant island is injected inbetween them, the relocation will clobber
1427 // the instruction and fail to update the MOVT instruction.
1428 // (These instructions are bundled up until right before the ConstantIslands
1429 // pass.)
1430 if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
1431 (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1432 ARMII::MO_HI16) {
1433 --MI;
1434 assert(MI->getOpcode() == ARM::t2MOVi16 &&
1435 (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1436 ARMII::MO_LO16);
1437 }
1438
Tim Northover631cc9c2014-11-13 17:58:53 +00001439 // We really must not split an IT block.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001440 LLVM_DEBUG(unsigned PredReg; assert(
1441 !isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001442
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001443 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001444}
1445
Jim Grosbach190e7b62012-03-23 23:07:03 +00001446/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001447/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001448/// place in-range. Return true if we changed any addresses (thus must run
1449/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001450bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1451 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001452 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001453 MachineInstr *UserMI = U.MI;
1454 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001455 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001456 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001457 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001458 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001459
Dale Johannesene18b13b2007-02-23 05:02:36 +00001460 // See if the current entry is within range, or there is a clone of it
1461 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001462 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001463 if (result==1) return false;
1464 else if (result==2) return true;
1465
1466 // No existing clone of this CPE is within range.
1467 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001468 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001469
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001470 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001471 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001472 MachineBasicBlock *NewMBB;
1473 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001474 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001475 LLVM_DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001476 MachineBasicBlock *WaterBB = *IP;
1477
1478 // If the original WaterList entry was "new water" on this iteration,
1479 // propagate that to the new island. This is just keeping NewWaterList
1480 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001481 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001482 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001483
Bob Wilson2f9be502009-10-15 20:49:47 +00001484 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001485 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001486 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001487 // No water found.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001488 LLVM_DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001489 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001490
Jim Grosbach190e7b62012-03-23 23:07:03 +00001491 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001492 // called while handling branches so that the water will be seen on the
1493 // next iteration for constant pools, but in this context, we don't want
1494 // it. Check for this so it will be removed from the WaterList.
1495 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001496 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001497 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001498 if (IP != WaterList.end())
1499 NewWaterList.erase(WaterBB);
1500
1501 // We are adding new water. Update NewWaterList.
1502 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001503 }
Sjoerd Meijerfc0d02c2018-02-27 19:26:02 +00001504 // Always align the new block because CP entries can be smaller than 4
1505 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1506 // be an already aligned constant pool block.
1507 const unsigned Align = isThumb ? 1 : 2;
1508 if (NewMBB->getAlignment() < Align)
1509 NewMBB->setAlignment(Align);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001510
Bob Wilson2f9be502009-10-15 20:49:47 +00001511 // Remove the original WaterList entry; we want subsequent insertions in
1512 // this vicinity to go after the one we're about to insert. This
1513 // considerably reduces the number of times we have to move the same CPE
1514 // more than once and is also important to ensure the algorithm terminates.
1515 if (IP != WaterList.end())
1516 WaterList.erase(IP);
1517
Dale Johannesene18b13b2007-02-23 05:02:36 +00001518 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001519 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001520
1521 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001522 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001523
Dale Johannesene18b13b2007-02-23 05:02:36 +00001524 // Now that we have an island to add the CPE to, clone the original CPE and
1525 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001526 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001527 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
Diana Picus116bbab2017-01-13 09:58:52 +00001528 .addImm(ID)
1529 .add(CPEMI->getOperand(1))
1530 .addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001531 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001532 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001533
Tim Northovera603c402015-05-31 19:22:07 +00001534 // Decrement the old entry, and remove it if refcount becomes 0.
1535 decrementCPEReferenceCount(CPI, CPEMI);
1536
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001537 // Mark the basic block as aligned as required by the const-pool entry.
1538 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001539
Evan Cheng10043e22007-01-19 07:51:42 +00001540 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001541 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001542 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001543
Evan Cheng10043e22007-01-19 07:51:42 +00001544 // Finally, change the CPI in the instruction operand to be ID.
1545 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001546 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001547 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001548 break;
1549 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001550
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001551 LLVM_DEBUG(
1552 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1553 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001554
Evan Cheng10043e22007-01-19 07:51:42 +00001555 return true;
1556}
1557
Jim Grosbach190e7b62012-03-23 23:07:03 +00001558/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001559/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001560void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001561 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001562 unsigned Size = CPEMI->getOperand(2).getImm();
1563 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001564 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001565 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001566 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001567 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001568
Evan Chengab28b9a2013-02-21 18:37:54 +00001569 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001570 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001571 } else
1572 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001573 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001574
Jim Grosbach190e7b62012-03-23 23:07:03 +00001575 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001576 // An island has only one predecessor BB and one successor BB. Check if
1577 // this BB's predecessor jumps directly to this BB's successor. This
1578 // shouldn't happen currently.
1579 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1580 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001581}
1582
Jim Grosbach190e7b62012-03-23 23:07:03 +00001583/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001584/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001585bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001586 unsigned MadeChange = false;
1587 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1588 std::vector<CPEntry> &CPEs = CPEntries[i];
1589 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1590 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001591 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001592 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001593 MadeChange = true;
1594 }
1595 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001596 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001597 return MadeChange;
1598}
1599
Jim Grosbach190e7b62012-03-23 23:07:03 +00001600/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001601/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001602bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001603 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001604 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001605 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001606 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001607
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001608 LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1609 << " from " << printMBBReference(*MI->getParent())
1610 << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1611 << " to " << DestOffset << " offset "
1612 << int(DestOffset - BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001613
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001614 if (BrOffset <= DestOffset) {
1615 // Branch before the Dest.
1616 if (DestOffset-BrOffset <= MaxDisp)
1617 return true;
1618 } else {
1619 if (BrOffset-DestOffset <= MaxDisp)
1620 return true;
1621 }
1622 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001623}
1624
Jim Grosbach190e7b62012-03-23 23:07:03 +00001625/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001626/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001627bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001628 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001629 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001630
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001631 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001632 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001633 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001634
Evan Cheng7fa69642007-01-30 01:18:38 +00001635 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001636 return fixupUnconditionalBr(Br);
1637 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001638}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001639
Jim Grosbach190e7b62012-03-23 23:07:03 +00001640/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001641/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001642/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001643/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001644bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001645ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001646 MachineInstr *MI = Br.MI;
1647 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001648 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001649 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001650
1651 // Use BL to implement far jump.
1652 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001653 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001654 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001655 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001656 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001657 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001658
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001659 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001660
Evan Cheng7fa69642007-01-30 01:18:38 +00001661 return true;
1662}
1663
Jim Grosbach190e7b62012-03-23 23:07:03 +00001664/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001665/// far away to fit in its displacement field. It is converted to an inverse
1666/// conditional branch + an unconditional branch to the destination.
1667bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001668ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001669 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001670 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001671
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001672 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001673 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001674 // blt L1
1675 // =>
1676 // bge L2
1677 // b L1
1678 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001679 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001680 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001681 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001682
1683 // If the branch is at the end of its MBB and that has a fall-through block,
1684 // direct the updated conditional branch to the fall-through block. Otherwise,
1685 // split the MBB before the next instruction.
1686 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001687 MachineInstr *BMI = &MBB->back();
1688 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001689
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001690 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001691 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001692 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001693 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001694 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001695 // condition and swap destinations:
1696 // beq L1
1697 // b L2
1698 // =>
1699 // bne L2
1700 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001701 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001702 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001703 LLVM_DEBUG(
1704 dbgs() << " Invert Bcc condition and swap its destination with "
1705 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001706 BMI->getOperand(0).setMBB(DestBB);
1707 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001708 MI->getOperand(1).setImm(CC);
1709 return true;
1710 }
1711 }
1712 }
1713
1714 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001715 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001716 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001717 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001718 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001719 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001720 MBB->back().eraseFromParent();
Tim Northover5cdc4f92017-11-14 11:43:54 +00001721
1722 // The conditional successor will be swapped between the BBs after this, so
1723 // update CFG.
1724 MBB->addSuccessor(DestBB);
1725 std::next(MBB->getIterator())->removeSuccessor(DestBB);
1726
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001727 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001728 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001729 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001730
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001731 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1732 << " also invert condition and change dest. to "
1733 << printMBBReference(*NextBB) << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001734
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001735 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001736 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001737 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001738 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001739 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001740 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001741 if (isThumb)
Diana Picusbd66b7d2017-01-20 08:15:24 +00001742 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1743 .addMBB(DestBB)
1744 .add(predOps(ARMCC::AL));
Owen Anderson93cd3182011-09-09 23:05:14 +00001745 else
1746 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001747 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001748 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001749 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001750
1751 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001752 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001753 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001754 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001755 return true;
1756}
Evan Cheng7fa69642007-01-30 01:18:38 +00001757
Jim Grosbach190e7b62012-03-23 23:07:03 +00001758/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001759/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1760/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001761bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001762 bool MadeChange = false;
1763 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1764 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001765 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001766 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001767 MI->getOperand(2).getReg() == ARM::PC &&
1768 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001769 // Create the new insn and copy the predicate from the old.
1770 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
Diana Picus116bbab2017-01-13 09:58:52 +00001771 .add(MI->getOperand(0))
1772 .add(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001773 MI->eraseFromParent();
1774 MadeChange = true;
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001775 } else if (MI->getOpcode() == ARM::tPUSH &&
1776 MI->getOperand(2).getReg() == ARM::LR &&
1777 MI->getNumExplicitOperands() == 3) {
Roger Ferrer Ibanez56db97d2017-02-22 09:06:21 +00001778 // Just remove the push.
1779 MI->eraseFromParent();
1780 MadeChange = true;
1781 }
Evan Cheng7fa69642007-01-30 01:18:38 +00001782 }
1783 return MadeChange;
1784}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001785
Jim Grosbach190e7b62012-03-23 23:07:03 +00001786bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001787 bool MadeChange = false;
1788
1789 // Shrink ADR and LDR from constantpool.
1790 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1791 CPUser &U = CPUsers[i];
1792 unsigned Opcode = U.MI->getOpcode();
1793 unsigned NewOpc = 0;
1794 unsigned Scale = 1;
1795 unsigned Bits = 0;
1796 switch (Opcode) {
1797 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001798 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001799 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1800 NewOpc = ARM::tLEApcrel;
1801 Bits = 8;
1802 Scale = 4;
1803 }
1804 break;
1805 case ARM::t2LDRpci:
1806 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1807 NewOpc = ARM::tLDRpci;
1808 Bits = 8;
1809 Scale = 4;
1810 }
1811 break;
1812 }
1813
1814 if (!NewOpc)
1815 continue;
1816
Jim Grosbach190e7b62012-03-23 23:07:03 +00001817 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001818 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001819
1820 // Be conservative with inline asm.
1821 if (!U.KnownAlignment)
1822 MaxOffs -= 2;
1823
Evan Chengdb73d682009-08-14 00:32:16 +00001824 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001825 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001826 LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001827 U.MI->setDesc(TII->get(NewOpc));
1828 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001829 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001830 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001831 ++NumT2CPShrunk;
1832 MadeChange = true;
1833 }
1834 }
1835
Evan Chengdb73d682009-08-14 00:32:16 +00001836 return MadeChange;
1837}
1838
Jim Grosbach190e7b62012-03-23 23:07:03 +00001839bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001840 bool MadeChange = false;
1841
Peter Collingbourne167668f2015-04-23 20:31:35 +00001842 // The order in which branches appear in ImmBranches is approximately their
1843 // order within the function body. By visiting later branches first, we reduce
1844 // the distance between earlier forward branches and their targets, making it
1845 // more likely that the cbn?z optimization, which can only apply to forward
1846 // branches, will succeed.
1847 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1848 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001849 unsigned Opcode = Br.MI->getOpcode();
1850 unsigned NewOpc = 0;
1851 unsigned Scale = 1;
1852 unsigned Bits = 0;
1853 switch (Opcode) {
1854 default: break;
1855 case ARM::t2B:
1856 NewOpc = ARM::tB;
1857 Bits = 11;
1858 Scale = 2;
1859 break;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001860 case ARM::t2Bcc:
Evan Chenge41903b2009-08-14 18:31:44 +00001861 NewOpc = ARM::tBcc;
1862 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001863 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001864 break;
1865 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001866 if (NewOpc) {
1867 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1868 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001869 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001870 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001871 Br.MI->setDesc(TII->get(NewOpc));
1872 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001873 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001874 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001875 ++NumT2BrShrunk;
1876 MadeChange = true;
1877 }
1878 }
1879
1880 Opcode = Br.MI->getOpcode();
1881 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001882 continue;
1883
Evan Cheng6bb95252012-01-14 01:53:46 +00001884 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1885 // so this transformation is not safe.
1886 if (!Br.MI->killsRegister(ARM::CPSR))
1887 continue;
1888
Evan Cheng6f29ad92009-10-31 23:46:45 +00001889 NewOpc = 0;
1890 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001891 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001892 if (Pred == ARMCC::EQ)
1893 NewOpc = ARM::tCBZ;
1894 else if (Pred == ARMCC::NE)
1895 NewOpc = ARM::tCBNZ;
1896 if (!NewOpc)
1897 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001898 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001899 // Check if the distance is within 126. Subtract starting offset by 2
1900 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001901 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001902 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001903 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001904 MachineBasicBlock::iterator CmpMI = Br.MI;
1905 if (CmpMI != Br.MI->getParent()->begin()) {
1906 --CmpMI;
1907 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1908 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001909 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001910 if (Pred == ARMCC::AL &&
1911 CmpMI->getOperand(1).getImm() == 0 &&
1912 isARMLowRegister(Reg)) {
1913 MachineBasicBlock *MBB = Br.MI->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001914 LLVM_DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001915 MachineInstr *NewBR =
1916 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1917 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1918 CmpMI->eraseFromParent();
1919 Br.MI->eraseFromParent();
1920 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001921 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001922 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001923 ++NumCBZ;
1924 MadeChange = true;
1925 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001926 }
1927 }
Evan Chenge41903b2009-08-14 18:31:44 +00001928 }
1929 }
1930
1931 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001932}
1933
Tim Northovera603c402015-05-31 19:22:07 +00001934static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1935 unsigned BaseReg) {
1936 if (I.getOpcode() != ARM::t2ADDrs)
1937 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001938
Tim Northovera603c402015-05-31 19:22:07 +00001939 if (I.getOperand(0).getReg() != EntryReg)
1940 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001941
Tim Northovera603c402015-05-31 19:22:07 +00001942 if (I.getOperand(1).getReg() != BaseReg)
1943 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001944
Tim Northovera603c402015-05-31 19:22:07 +00001945 // FIXME: what about CC and IdxReg?
1946 return true;
1947}
Tim Northover688f7bb2015-05-13 20:28:32 +00001948
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001949/// While trying to form a TBB/TBH instruction, we may (if the table
Tim Northovera603c402015-05-31 19:22:07 +00001950/// doesn't immediately follow the BR_JT) need access to the start of the
1951/// jump-table. We know one instruction that produces such a register; this
1952/// function works out whether that definition can be preserved to the BR_JT,
1953/// possibly by removing an intervening addition (which is usually needed to
1954/// calculate the actual entry to jump to).
1955bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1956 MachineInstr *LEAMI,
1957 unsigned &DeadSize,
1958 bool &CanDeleteLEA,
1959 bool &BaseRegKill) {
1960 if (JumpMI->getParent() != LEAMI->getParent())
1961 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001962
Tim Northovera603c402015-05-31 19:22:07 +00001963 // Now we hope that we have at least these instructions in the basic block:
1964 // BaseReg = t2LEA ...
1965 // [...]
1966 // EntryReg = t2ADDrs BaseReg, ...
1967 // [...]
1968 // t2BR_JT EntryReg
1969 //
1970 // We have to be very conservative about what we recognise here though. The
1971 // main perturbing factors to watch out for are:
1972 // + Spills at any point in the chain: not direct problems but we would
1973 // expect a blocking Def of the spilled register so in practice what we
1974 // can do is limited.
1975 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1976 // of BaseReg, but only if the t2ADDrs can be removed.
1977 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1978 // the wild, but we should be careful.
1979 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1980 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1981
1982 CanDeleteLEA = true;
1983 BaseRegKill = false;
1984 MachineInstr *RemovableAdd = nullptr;
1985 MachineBasicBlock::iterator I(LEAMI);
1986 for (++I; &*I != JumpMI; ++I) {
1987 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1988 RemovableAdd = &*I;
1989 break;
1990 }
1991
1992 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1993 const MachineOperand &MO = I->getOperand(K);
1994 if (!MO.isReg() || !MO.getReg())
1995 continue;
1996 if (MO.isDef() && MO.getReg() == BaseReg)
1997 return false;
1998 if (MO.isUse() && MO.getReg() == BaseReg) {
1999 BaseRegKill = BaseRegKill || MO.isKill();
2000 CanDeleteLEA = false;
2001 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002002 }
2003 }
2004
Tim Northovera603c402015-05-31 19:22:07 +00002005 if (!RemovableAdd)
2006 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00002007
Tim Northovera603c402015-05-31 19:22:07 +00002008 // Check the add really is removable, and that nothing else in the block
2009 // clobbers BaseReg.
2010 for (++I; &*I != JumpMI; ++I) {
2011 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2012 const MachineOperand &MO = I->getOperand(K);
2013 if (!MO.isReg() || !MO.getReg())
2014 continue;
2015 if (MO.isDef() && MO.getReg() == BaseReg)
2016 return false;
2017 if (MO.isUse() && MO.getReg() == EntryReg)
2018 RemovableAdd = nullptr;
2019 }
2020 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002021
Tim Northovera603c402015-05-31 19:22:07 +00002022 if (RemovableAdd) {
2023 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002024 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002025 } else if (BaseReg == EntryReg) {
2026 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2027 // preserve it.
2028 return false;
2029 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002030
Tim Northovera603c402015-05-31 19:22:07 +00002031 // We reached the end of the block without seeing another definition of
2032 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2033 // used in the TBB/TBH if necessary.
2034 return true;
2035}
Tim Northover688f7bb2015-05-13 20:28:32 +00002036
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002037/// Returns whether CPEMI is the first instruction in the block
Tim Northovera603c402015-05-31 19:22:07 +00002038/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2039/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002040/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002041static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002042 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002043 MachineFunction *MF = MBB->getParent();
2044 ++MBB;
2045
2046 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2047 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002048}
2049
David Green1b4b59a2017-04-06 08:32:47 +00002050static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
2051 MachineInstr *JumpMI,
2052 unsigned &DeadSize) {
2053 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2054 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2055 // and is not clobbered / used.
2056 MachineInstr *RemovableAdd = nullptr;
2057 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2058
2059 // Find the last ADD to set EntryReg
2060 MachineBasicBlock::iterator I(LEAMI);
2061 for (++I; &*I != JumpMI; ++I) {
2062 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2063 RemovableAdd = &*I;
2064 }
2065
2066 if (!RemovableAdd)
2067 return;
2068
2069 // Ensure EntryReg is not clobbered or used.
2070 MachineBasicBlock::iterator J(RemovableAdd);
2071 for (++J; &*J != JumpMI; ++J) {
2072 for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2073 const MachineOperand &MO = J->getOperand(K);
2074 if (!MO.isReg() || !MO.getReg())
2075 continue;
2076 if (MO.isDef() && MO.getReg() == EntryReg)
2077 return;
2078 if (MO.isUse() && MO.getReg() == EntryReg)
2079 return;
2080 }
2081 }
2082
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002083 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
David Green1b4b59a2017-04-06 08:32:47 +00002084 RemovableAdd->eraseFromParent();
2085 DeadSize += 4;
2086}
2087
James Molloy92497542017-02-13 14:07:39 +00002088static bool registerDefinedBetween(unsigned Reg,
2089 MachineBasicBlock::iterator From,
2090 MachineBasicBlock::iterator To,
2091 const TargetRegisterInfo *TRI) {
2092 for (auto I = From; I != To; ++I)
2093 if (I->modifiesRegister(Reg, TRI))
2094 return true;
2095 return false;
2096}
2097
Jim Grosbach190e7b62012-03-23 23:07:03 +00002098/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002099/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002100bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002101 bool MadeChange = false;
2102
2103 // FIXME: After the tables are shrunk, can we get rid some of the
2104 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002105 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002106 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002107
Evan Chengc6d70ae2009-07-29 02:18:14 +00002108 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2109 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2110 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002111 const MCInstrDesc &MCID = MI->getDesc();
2112 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002113 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002114 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2115 unsigned JTI = JTOP.getIndex();
2116 assert(JTI < JT.size());
2117
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002118 bool ByteOk = true;
2119 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002120 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002121 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002122 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2123 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002124 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002125 // Negative offset is not ok. FIXME: We should change BB layout to make
2126 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002127 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002128 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002129 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002130 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002131 HalfWordOk = false;
2132 if (!ByteOk && !HalfWordOk)
2133 break;
2134 }
2135
Tim Northovera603c402015-05-31 19:22:07 +00002136 if (!ByteOk && !HalfWordOk)
2137 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002138
James Molloy70a3d6d2016-11-01 13:37:41 +00002139 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002140 MachineBasicBlock *MBB = MI->getParent();
2141 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2142 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002143
Tim Northovera603c402015-05-31 19:22:07 +00002144 unsigned DeadSize = 0;
2145 bool CanDeleteLEA = false;
2146 bool BaseRegKill = false;
Fangrui Songf78650a2018-07-30 19:41:25 +00002147
James Molloy70a3d6d2016-11-01 13:37:41 +00002148 unsigned IdxReg = ~0U;
2149 bool IdxRegKill = true;
2150 if (isThumb2) {
2151 IdxReg = MI->getOperand(1).getReg();
2152 IdxRegKill = MI->getOperand(1).isKill();
2153
2154 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002155 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002156 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2157 continue;
2158 } else {
2159 // We're in thumb-1 mode, so we must have something like:
2160 // %idx = tLSLri %idx, 2
2161 // %base = tLEApcrelJT
Momchil Velikov842aa902017-11-13 11:56:48 +00002162 // %t = tLDRr %base, %idx
James Molloy70a3d6d2016-11-01 13:37:41 +00002163 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002164
James Molloy70a3d6d2016-11-01 13:37:41 +00002165 if (User.MI->getIterator() == User.MI->getParent()->begin())
2166 continue;
2167 MachineInstr *Shift = User.MI->getPrevNode();
2168 if (Shift->getOpcode() != ARM::tLSLri ||
2169 Shift->getOperand(3).getImm() != 2 ||
2170 !Shift->getOperand(2).isKill())
2171 continue;
2172 IdxReg = Shift->getOperand(2).getReg();
2173 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002174
Tim Northover0d98b032017-03-15 18:38:13 +00002175 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2176 // the range is checked later, but the LEA might still clobber it and not
2177 // actually get removed.
2178 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2179 continue;
2180
James Molloy70a3d6d2016-11-01 13:37:41 +00002181 MachineInstr *Load = User.MI->getNextNode();
2182 if (Load->getOpcode() != ARM::tLDRr)
2183 continue;
Momchil Velikov842aa902017-11-13 11:56:48 +00002184 if (Load->getOperand(1).getReg() != BaseReg ||
2185 Load->getOperand(2).getReg() != ShiftedIdxReg ||
2186 !Load->getOperand(2).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002187 continue;
2188
2189 // If we're in PIC mode, there should be another ADD following.
James Molloy92497542017-02-13 14:07:39 +00002190 auto *TRI = STI->getRegisterInfo();
Weiming Zhao962c5a32017-04-20 18:37:14 +00002191
2192 // %base cannot be redefined after the load as it will appear before
2193 // TBB/TBH like:
2194 // %base =
2195 // %base =
2196 // tBB %base, %idx
2197 if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2198 continue;
2199
James Molloy70a3d6d2016-11-01 13:37:41 +00002200 if (isPositionIndependentOrROPI) {
2201 MachineInstr *Add = Load->getNextNode();
2202 if (Add->getOpcode() != ARM::tADDrr ||
Momchil Velikov842aa902017-11-13 11:56:48 +00002203 Add->getOperand(2).getReg() != BaseReg ||
2204 Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2205 !Add->getOperand(3).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002206 continue;
2207 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2208 continue;
James Molloy92497542017-02-13 14:07:39 +00002209 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2210 // IdxReg gets redefined in the middle of the sequence.
2211 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002212 Add->eraseFromParent();
2213 DeadSize += 2;
2214 } else {
2215 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2216 continue;
James Molloy92497542017-02-13 14:07:39 +00002217 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2218 // IdxReg gets redefined in the middle of the sequence.
2219 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002220 }
Tim Northover0d98b032017-03-15 18:38:13 +00002221
James Molloy70a3d6d2016-11-01 13:37:41 +00002222 // Now safe to delete the load and lsl. The LEA will be removed later.
2223 CanDeleteLEA = true;
2224 Shift->eraseFromParent();
2225 Load->eraseFromParent();
2226 DeadSize += 4;
2227 }
Tim Northover0d98b032017-03-15 18:38:13 +00002228
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002229 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
Tim Northovera603c402015-05-31 19:22:07 +00002230 MachineInstr *CPEMI = User.CPEMI;
2231 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002232 if (!isThumb2)
2233 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2234
Tim Northovera603c402015-05-31 19:22:07 +00002235 MachineBasicBlock::iterator MI_JT = MI;
2236 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002237 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002238 .addReg(User.MI->getOperand(0).getReg(),
2239 getKillRegState(BaseRegKill))
2240 .addReg(IdxReg, getKillRegState(IdxRegKill))
2241 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2242 .addImm(CPEMI->getOperand(0).getImm());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002243 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002244
Tim Northovera603c402015-05-31 19:22:07 +00002245 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2246 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002247
Tim Northovera603c402015-05-31 19:22:07 +00002248 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2249 NewJTMI->getOperand(0).setReg(ARM::PC);
2250 NewJTMI->getOperand(0).setIsKill(false);
2251
David Green1b4b59a2017-04-06 08:32:47 +00002252 if (CanDeleteLEA) {
2253 if (isThumb2)
2254 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2255
Tim Northovera603c402015-05-31 19:22:07 +00002256 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002257 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002258
2259 // The LEA was eliminated, the TBB instruction becomes the only new user
2260 // of the jump table.
2261 User.MI = NewJTMI;
2262 User.MaxDisp = 4;
2263 User.NegOk = false;
2264 User.IsSoImm = false;
2265 User.KnownAlignment = false;
2266 } else {
2267 // The LEA couldn't be eliminated, so we must add another CPUser to
2268 // record the TBB or TBH use.
2269 int CPEntryIdx = JumpTableEntryIndices[JTI];
2270 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002271 auto Entry =
2272 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002273 ++Entry->RefCount;
2274 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2275 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002276 }
Tim Northovera603c402015-05-31 19:22:07 +00002277
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002278 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2279 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002280 MI->eraseFromParent();
2281
2282 int Delta = OrigSize - NewSize + DeadSize;
2283 BBInfo[MBB->getNumber()].Size -= Delta;
2284 adjustBBOffsetsAfter(MBB);
2285
2286 ++NumTBs;
2287 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002288 }
2289
2290 return MadeChange;
2291}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002292
Jim Grosbach190e7b62012-03-23 23:07:03 +00002293/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002294/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002295bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002296 bool MadeChange = false;
2297
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002298 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002299 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002300
Jim Grosbach5d577142009-11-12 17:25:07 +00002301 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2302 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2303 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002304 const MCInstrDesc &MCID = MI->getDesc();
2305 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002306 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002307 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2308 unsigned JTI = JTOP.getIndex();
2309 assert(JTI < JT.size());
2310
2311 // We prefer if target blocks for the jump table come after the jump
2312 // instruction so we can use TB[BH]. Loop through the target blocks
2313 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002314 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002315 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2316 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2317 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002318 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002319
Jim Grosbach9785e592009-11-16 18:58:52 +00002320 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002321 // The destination precedes the switch. Try to move the block forward
2322 // so we have a positive offset.
2323 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002324 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002325 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002326 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002327 MadeChange = true;
2328 }
2329 }
2330 }
2331
2332 return MadeChange;
2333}
2334
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002335MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002336adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002337 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002338 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002339 // table that branches back to the actual target. This is a very simple
2340 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002341 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002342 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002343 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002344 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002345 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002346
Jim Grosbach47d5e332009-11-16 17:10:56 +00002347 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002348 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002349
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002350 // If the block ends in an unconditional branch, move it. The prior block
2351 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002352 // 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 +00002353 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002354 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002355 BB->moveAfter(JTBB);
2356 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002357 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002358 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002359 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002360 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002361 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002362 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002363
2364 // Create a new MBB for the code after the jump BB.
2365 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002366 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002367 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002368 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002369
2370 // Add an unconditional branch from NewBB to BB.
2371 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2372 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002373 if (isThumb2)
2374 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2375 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002376 .add(predOps(ARMCC::AL));
James Molloy70a3d6d2016-11-01 13:37:41 +00002377 else
2378 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2379 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002380 .add(predOps(ARMCC::AL));
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002381
Jim Grosbach43d21082009-11-14 20:10:18 +00002382 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002383 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002384
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002385 // Update the CFG.
2386 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002387 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002388
Jim Grosbach5d577142009-11-12 17:25:07 +00002389 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002390 return NewBB;
2391}
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002392
2393/// createARMConstantIslandPass - returns an instance of the constpool
2394/// island pass.
2395FunctionPass *llvm::createARMConstantIslandPass() {
2396 return new ARMConstantIslands();
2397}
James Molloy9b3b8992017-02-13 14:07:25 +00002398
2399INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2400 false, false)