blob: 3e4e732ddb9d497393635533ea899cca2292b297 [file] [log] [blame]
Bill Wendling9a4d2e42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Chenga8e29892007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Chenga8e29892007-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
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000019#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000020#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000021#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000029#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
Jakob Stoklund Olesenf5bb45f2011-12-16 16:07:41 +000055// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000056static cl::opt<bool>
Jakob Stoklund Olesenb6ff6ec2011-12-15 22:14:45 +000057AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000058 cl::desc("Align constant islands in code"));
59
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000060/// UnknownPadding - Return the worst case padding that could result from
61/// unknown offset bits. This does not include alignment padding caused by
62/// known offset bits.
63///
64/// @param LogAlign log2(alignment)
65/// @param KnownBits Number of known low offset bits.
66static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67 if (KnownBits < LogAlign)
68 return (1u << LogAlign) - (1u << KnownBits);
69 return 0;
70}
71
Evan Chenga8e29892007-01-19 07:51:42 +000072namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000073 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000074 /// requires constant pool entries to be scattered among the instructions
75 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000076 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000077 /// special instructions.
78 ///
79 /// The terminology used in this pass includes:
80 /// Islands - Clumps of constants placed in the function.
81 /// Water - Potential places where an island could be formed.
82 /// CPE - A constant pool entry that has been placed somewhere, which
83 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000084 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000085 /// BasicBlockInfo - Information about the offset and size of a single
86 /// basic block.
87 struct BasicBlockInfo {
88 /// Offset - Distance from the beginning of the function to the beginning
89 /// of this basic block.
90 ///
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +000091 /// Offsets are computed assuming worst case padding before an aligned
92 /// block. This means that subtracting basic block offsets always gives a
93 /// conservative estimate of the real distance which may be smaller.
94 ///
95 /// Because worst case padding is used, the computed offset of an aligned
96 /// block may not actually be aligned.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000097 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +000098
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000099 /// Size - Size of the basic block in bytes. If the block contains
100 /// inline assembly, this is a worst case estimate.
101 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000102 /// The size does not include any alignment padding whether from the
103 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000104 unsigned Size;
105
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000106 /// KnownBits - The number of low bits in Offset that are known to be
107 /// exact. The remaining bits of Offset are an upper bound.
108 uint8_t KnownBits;
109
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000110 /// Unalign - When non-zero, the block contains instructions (inline asm)
111 /// of unknown size. The real size may be smaller than Size bytes by a
112 /// multiple of 1 << Unalign.
113 uint8_t Unalign;
114
115 /// PostAlign - When non-zero, the block terminator contains a .align
116 /// directive, so the end of the block is aligned to 1 << PostAlign
117 /// bytes.
118 uint8_t PostAlign;
119
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000120 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
121 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000122
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000123 /// Compute the number of known offset bits internally to this block.
124 /// This number should be used to predict worst case padding when
125 /// splitting the block.
126 unsigned internalKnownBits() const {
127 return Unalign ? Unalign : KnownBits;
128 }
129
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000130 /// Compute the offset immediately following this block. If LogAlign is
131 /// specified, return the offset the successor block will get if it has
132 /// this alignment.
133 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000134 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000135 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
136 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000137 return PO;
138 // Add alignment padding from the terminator.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +0000139 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000140 }
141
142 /// Compute the number of known low bits of postOffset. If this block
143 /// contains inline asm, the number of known bits drops to the
144 /// instruction alignment. An aligned terminator may increase the number
145 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000146 /// If LogAlign is given, also consider the alignment of the next block.
147 unsigned postKnownBits(unsigned LogAlign = 0) const {
148 return std::max(std::max(unsigned(PostAlign), LogAlign),
149 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000150 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000151 };
152
153 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000154
Evan Chenga8e29892007-01-19 07:51:42 +0000155 /// WaterList - A sorted list of basic blocks where islands could be placed
156 /// (i.e. blocks that don't fall through to the following block, due
157 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000158 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000159
Bob Wilsonb9239532009-10-15 20:49:47 +0000160 /// NewWaterList - The subset of WaterList that was created since the
161 /// previous iteration by inserting unconditional branches.
162 SmallSet<MachineBasicBlock*, 4> NewWaterList;
163
Bob Wilson034de5f2009-10-12 18:52:13 +0000164 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
165
Evan Chenga8e29892007-01-19 07:51:42 +0000166 /// CPUser - One user of a constant pool, keeping the machine instruction
167 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000168 /// allowed from the instruction to the CP. The HighWaterMark records the
169 /// highest basic block where a new CPEntry can be placed. To ensure this
170 /// pass terminates, the CP entries are initially placed at the end of the
171 /// function and then move monotonically to lower addresses. The
172 /// exception to this rule is when the current CP entry for a particular
173 /// CPUser is out of range, but there is another CP entry for the same
174 /// constant value in range. We want to use the existing in-range CP
175 /// entry, but if it later moves out of range, the search for new water
176 /// should resume where it left off. The HighWaterMark is used to record
177 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000178 struct CPUser {
179 MachineInstr *MI;
180 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000181 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000182 private:
Evan Chenga8e29892007-01-19 07:51:42 +0000183 unsigned MaxDisp;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000184 public:
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000185 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000186 bool IsSoImm;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000187 bool KnownAlignment;
Evan Chengd3d9d662009-07-23 18:27:47 +0000188 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
189 bool neg, bool soimm)
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000190 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
191 KnownAlignment(false) {
Bob Wilson549dda92009-10-15 05:52:29 +0000192 HighWaterMark = CPEMI->getParent();
193 }
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000194 /// getMaxDisp - Returns the maximum displacement supported by MI.
195 /// Correct for unknown alignment.
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000196 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000197 unsigned getMaxDisp() const {
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000198 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000199 }
Evan Chenga8e29892007-01-19 07:51:42 +0000200 };
Bob Wilson84945262009-05-12 17:09:30 +0000201
Evan Chenga8e29892007-01-19 07:51:42 +0000202 /// CPUsers - Keep track of all of the machine instructions that use various
203 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000204 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000205
Evan Chengc99ef082007-02-09 20:54:44 +0000206 /// CPEntry - One per constant pool entry, keeping the machine instruction
207 /// pointer, the constpool index, and the number of CPUser's which
208 /// reference this entry.
209 struct CPEntry {
210 MachineInstr *CPEMI;
211 unsigned CPI;
212 unsigned RefCount;
213 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
214 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
215 };
216
217 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000218 /// instructions. For each original constpool index (i.e. those that
219 /// existed upon entry to this pass), it keeps a vector of entries.
220 /// Original elements are cloned as we go along; the clones are
221 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000222 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000223
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000224 /// ImmBranch - One per immediate branch, keeping the machine instruction
225 /// pointer, conditional or unconditional, the max displacement,
226 /// and (if isCond is true) the corresponding unconditional branch
227 /// opcode.
228 struct ImmBranch {
229 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000230 unsigned MaxDisp : 31;
231 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000232 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000233 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
234 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000235 };
236
Evan Cheng2706f972007-05-16 05:14:06 +0000237 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000239 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000240
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000241 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
242 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000243 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000244
Evan Cheng5657c012009-07-29 02:18:14 +0000245 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
246 SmallVector<MachineInstr*, 4> T2JumpTables;
247
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000248 /// HasFarJump - True if any far jump instruction has been emitted during
249 /// the branch fix up pass.
250 bool HasFarJump;
251
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000252 MachineFunction *MF;
253 MachineConstantPool *MCP;
Craig Topperacf20772012-03-25 23:49:58 +0000254 const ARMBaseInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000255 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000256 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000257 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000258 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000259 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000260 public:
Devang Patel19974732007-05-03 01:11:54 +0000261 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000262 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000263
Evan Cheng5657c012009-07-29 02:18:14 +0000264 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000265
266 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000267 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000268 }
Bob Wilson84945262009-05-12 17:09:30 +0000269
Evan Chenga8e29892007-01-19 07:51:42 +0000270 private:
Jim Grosbach7a465252012-03-23 23:07:03 +0000271 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000272 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000273 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach7a465252012-03-23 23:07:03 +0000274 void scanFunctionJumpTables();
275 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
276 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
277 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
278 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
279 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
280 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
281 bool findAvailableWater(CPUser&U, unsigned UserOffset,
282 water_iterator &WaterIter);
283 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000284 MachineBasicBlock *&NewMBB);
Jim Grosbach7a465252012-03-23 23:07:03 +0000285 bool handleConstantPoolUser(unsigned CPUserIndex);
286 void removeDeadCPEMI(MachineInstr *CPEMI);
287 bool removeUnusedCPEntries();
288 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
289 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
290 bool DoDump = false);
291 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000292 CPUser &U, unsigned &Growth);
Jim Grosbach7a465252012-03-23 23:07:03 +0000293 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
294 bool fixupImmediateBr(ImmBranch &Br);
295 bool fixupConditionalBr(ImmBranch &Br);
296 bool fixupUnconditionalBr(ImmBranch &Br);
297 bool undoLRSpillRestore();
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000298 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach7a465252012-03-23 23:07:03 +0000299 bool optimizeThumb2Instructions();
300 bool optimizeThumb2Branches();
301 bool reorderThumb2JumpTables();
302 bool optimizeThumb2JumpTables();
303 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000304 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000305
Jim Grosbach7a465252012-03-23 23:07:03 +0000306 void computeBlockSize(MachineBasicBlock *MBB);
307 unsigned getOffsetOf(MachineInstr *MI) const;
308 unsigned getUserOffset(CPUser&) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000309 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000310 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000311
Jim Grosbach7a465252012-03-23 23:07:03 +0000312 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000313 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach7a465252012-03-23 23:07:03 +0000314 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000315 const CPUser &U) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000316 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000317 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000318 }
Evan Chenga8e29892007-01-19 07:51:42 +0000319 };
Devang Patel19974732007-05-03 01:11:54 +0000320 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000321}
322
Dale Johannesen8593e412007-04-29 19:19:30 +0000323/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000324void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000325#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000326 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000327 MBBI != E; ++MBBI) {
328 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000329 unsigned MBBId = MBB->getNumber();
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000330 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000331 }
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000332 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000333 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
334 CPUser &U = CPUsers[i];
Jim Grosbach7a465252012-03-23 23:07:03 +0000335 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000336 // Verify offset using the real max displacement without the safety
337 // adjustment.
338 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000339 /* DoDump = */ true)) {
340 DEBUG(dbgs() << "OK\n");
341 continue;
342 }
343 DEBUG(dbgs() << "Out of range.\n");
344 dumpBBs();
345 DEBUG(MF->dump());
346 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000347 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000348#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000349}
350
351/// print block size and offset information - debugging
352void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000353 DEBUG({
354 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
355 const BasicBlockInfo &BBI = BBInfo[J];
356 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
357 << " kb=" << unsigned(BBI.KnownBits)
358 << " ua=" << unsigned(BBI.Unalign)
359 << " pa=" << unsigned(BBI.PostAlign)
360 << format(" size=%#x\n", BBInfo[J].Size);
361 }
362 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000363}
364
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000365/// createARMConstantIslandPass - returns an instance of the constpool
366/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000367FunctionPass *llvm::createARMConstantIslandPass() {
368 return new ARMConstantIslands();
369}
370
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000371bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
372 MF = &mf;
373 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000374
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000375 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000376 << MCP->getConstants().size() << " CP entries, aligned to "
377 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000378
Craig Topperacf20772012-03-25 23:49:58 +0000379 TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000380 AFI = MF->getInfo<ARMFunctionInfo>();
381 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000382
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000383 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000384 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000385 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000386
387 HasFarJump = false;
388
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +0000389 // This pass invalidates liveness information when it splits basic blocks.
390 MF->getRegInfo().invalidateLiveness();
391
Evan Chenga8e29892007-01-19 07:51:42 +0000392 // Renumber all of the machine basic blocks in the function, guaranteeing that
393 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000394 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000395
Jim Grosbach80697d12009-11-12 17:25:07 +0000396 // Try to reorder and otherwise adjust the block layout to make good use
397 // of the TB[BH] instructions.
398 bool MadeChange = false;
399 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000400 scanFunctionJumpTables();
401 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000402 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000403 T2JumpTables.clear();
404 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000405 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000406 }
407
Evan Chengd26b14c2009-07-31 18:28:05 +0000408 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000409 // This is so we can keep exact track of where the alignment padding goes.
410
Chris Lattner7d7dab02010-01-27 23:37:36 +0000411 // ARM and Thumb2 functions need to be 4-byte aligned.
412 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000413 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000414
Evan Chenga8e29892007-01-19 07:51:42 +0000415 // Perform the initial placement of the constant pool entries. To start with,
416 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000417 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000418 if (!MCP->isEmpty())
Jim Grosbach7a465252012-03-23 23:07:03 +0000419 doInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000420
Evan Chenga8e29892007-01-19 07:51:42 +0000421 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000422 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000423
Evan Chenga8e29892007-01-19 07:51:42 +0000424 // Do the initial scan of the function, building up information about the
425 // sizes of each block, the location of all the water, and finding all of the
426 // constant pool users.
Jim Grosbach7a465252012-03-23 23:07:03 +0000427 initializeFunctionInfo(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000428 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000429 DEBUG(dumpBBs());
430
Bob Wilson84945262009-05-12 17:09:30 +0000431
Evan Chenged884f32007-04-03 23:39:48 +0000432 /// Remove dead constant pool entries.
Jim Grosbach7a465252012-03-23 23:07:03 +0000433 MadeChange |= removeUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000434
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000435 // Iteratively place constant pool entries and fix up branches until there
436 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000437 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000438 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000439 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000440 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000441 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000442 CPChange |= handleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000443 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000444 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000445 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000446
Bob Wilsonb9239532009-10-15 20:49:47 +0000447 // Clear NewWaterList now. If we split a block for branches, it should
448 // appear as "new water" for the next iteration of constant pool placement.
449 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000450
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000451 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000452 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000453 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000454 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000455 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000456 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000457 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000458
459 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000460 break;
461 MadeChange = true;
462 }
Evan Chenged884f32007-04-03 23:39:48 +0000463
Evan Chenga1efbbd2009-08-14 00:32:16 +0000464 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000465 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach7a465252012-03-23 23:07:03 +0000466 MadeChange |= optimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000467
Dale Johannesen8593e412007-04-29 19:19:30 +0000468 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000469 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000470
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000471 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
472 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000473 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach7a465252012-03-23 23:07:03 +0000474 MadeChange |= undoLRSpillRestore();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000475
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000476 // Save the mapping between original and cloned constpool entries.
477 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
478 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
479 const CPEntry & CPE = CPEntries[i][j];
480 AFI->recordCPEClone(i, CPE.CPI);
481 }
482 }
483
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000484 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000485
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000486 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000487 WaterList.clear();
488 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000489 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000490 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000491 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000492 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000493
494 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000495}
496
Jim Grosbach7a465252012-03-23 23:07:03 +0000497/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Chenga8e29892007-01-19 07:51:42 +0000498/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000499void
Jim Grosbach7a465252012-03-23 23:07:03 +0000500ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000501 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000502 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
503 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000504
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000505 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000506 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000507
508 // Mark the basic block as required by the const-pool.
509 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
510 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
511
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000512 // The function needs to be as aligned as the basic blocks. The linker may
513 // move functions around based on their alignment.
514 MF->EnsureAlignment(BB->getAlignment());
515
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000516 // Order the entries in BB by descending alignment. That ensures correct
517 // alignment of all entries as long as BB is sufficiently aligned. Keep
518 // track of the insertion point for each alignment. We are going to bucket
519 // sort the entries as they are created.
520 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000521
Evan Chenga8e29892007-01-19 07:51:42 +0000522 // Add all of the constants from the constant pool to the end block, use an
523 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000524 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000525
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000526 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000527 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000528 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000529 assert(Size >= 4 && "Too small constant pool entry");
530 unsigned Align = CPs[i].getAlignment();
531 assert(isPowerOf2_32(Align) && "Invalid alignment");
532 // Verify that all constant pool entries are a multiple of their alignment.
533 // If not, we would have to pad them out so that instructions stay aligned.
534 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
535
536 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
537 unsigned LogAlign = Log2_32(Align);
538 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000539 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000540 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000541 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000542 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000543
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000544 // Ensure that future entries with higher alignment get inserted before
545 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000546 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000547 if (InsPoint[a] == InsAt)
548 InsPoint[a] = CPEMI;
549
Evan Chengc99ef082007-02-09 20:54:44 +0000550 // Add a new CPEntry, but no corresponding CPUser yet.
551 std::vector<CPEntry> CPEs;
552 CPEs.push_back(CPEntry(CPEMI, i));
553 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000554 ++NumCPEs;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000555 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
556 << Size << ", align = " << Align <<'\n');
Evan Chenga8e29892007-01-19 07:51:42 +0000557 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000558 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000559}
560
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000561/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000562/// into the block immediately after it.
563static bool BBHasFallthrough(MachineBasicBlock *MBB) {
564 // Get the next machine basic block in the function.
565 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000566 // Can't fall off end of function.
567 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000568 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000569
Chris Lattner7896c9f2009-12-03 00:50:42 +0000570 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000571 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
572 E = MBB->succ_end(); I != E; ++I)
573 if (*I == NextBB)
574 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000575
Evan Chenga8e29892007-01-19 07:51:42 +0000576 return false;
577}
578
Evan Chengc99ef082007-02-09 20:54:44 +0000579/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
580/// look up the corresponding CPEntry.
581ARMConstantIslands::CPEntry
582*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
583 const MachineInstr *CPEMI) {
584 std::vector<CPEntry> &CPEs = CPEntries[CPI];
585 // Number of entries per constpool index should be small, just do a
586 // linear search.
587 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
588 if (CPEs[i].CPEMI == CPEMI)
589 return &CPEs[i];
590 }
591 return NULL;
592}
593
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000594/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000595/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000596unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
597 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
598
599 // Everything is 4-byte aligned unless AlignConstantIslands is set.
600 if (!AlignConstantIslands)
601 return 2;
602
603 unsigned CPI = CPEMI->getOperand(1).getIndex();
604 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
605 unsigned Align = MCP->getConstants()[CPI].getAlignment();
606 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
607 return Log2_32(Align);
608}
609
Jim Grosbach7a465252012-03-23 23:07:03 +0000610/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach80697d12009-11-12 17:25:07 +0000611/// information about the sizes of each block and the locations of all
612/// the jump tables.
Jim Grosbach7a465252012-03-23 23:07:03 +0000613void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000614 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000615 MBBI != E; ++MBBI) {
616 MachineBasicBlock &MBB = *MBBI;
617
Jim Grosbach80697d12009-11-12 17:25:07 +0000618 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000619 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000620 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000621 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000622 }
623}
624
Jim Grosbach7a465252012-03-23 23:07:03 +0000625/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Chenga8e29892007-01-19 07:51:42 +0000626/// information about the sizes of each block, the location of all the water,
627/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000628void ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +0000629initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000630 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000631 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000632
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000633 // First thing, compute the size of all basic blocks, and see if the function
634 // has any inline assembly in it. If so, we have to be conservative about
635 // alignment assumptions, as we don't know for sure the size of any
636 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000637 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach7a465252012-03-23 23:07:03 +0000638 computeBlockSize(I);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000639
640 // The known bits of the entry block offset are determined by the function
641 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000642 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000643
644 // Compute block offsets and known bits.
Jim Grosbach7a465252012-03-23 23:07:03 +0000645 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000646
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000647 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000648 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000649 MBBI != E; ++MBBI) {
650 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000651
Evan Chenga8e29892007-01-19 07:51:42 +0000652 // If this block doesn't fall through into the next MBB, then this is
653 // 'water' that a constant pool island could be placed.
654 if (!BBHasFallthrough(&MBB))
655 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000656
Evan Chenga8e29892007-01-19 07:51:42 +0000657 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
658 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000659 if (I->isDebugValue())
660 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000661
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000662 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000663 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000664 bool isCond = false;
665 unsigned Bits = 0;
666 unsigned Scale = 1;
667 int UOpc = Opc;
668 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000669 default:
670 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000671 case ARM::t2BR_JT:
672 T2JumpTables.push_back(I);
673 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000674 case ARM::Bcc:
675 isCond = true;
676 UOpc = ARM::B;
677 // Fallthrough
678 case ARM::B:
679 Bits = 24;
680 Scale = 4;
681 break;
682 case ARM::tBcc:
683 isCond = true;
684 UOpc = ARM::tB;
685 Bits = 8;
686 Scale = 2;
687 break;
688 case ARM::tB:
689 Bits = 11;
690 Scale = 2;
691 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000692 case ARM::t2Bcc:
693 isCond = true;
694 UOpc = ARM::t2B;
695 Bits = 20;
696 Scale = 2;
697 break;
698 case ARM::t2B:
699 Bits = 24;
700 Scale = 2;
701 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000702 }
Evan Chengb43216e2007-02-01 10:16:15 +0000703
704 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000705 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000706 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000707 }
708
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000709 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
710 PushPopMIs.push_back(I);
711
Evan Chengd3d9d662009-07-23 18:27:47 +0000712 if (Opc == ARM::CONSTPOOL_ENTRY)
713 continue;
714
Evan Chenga8e29892007-01-19 07:51:42 +0000715 // Scan the instructions for constant pool operands.
716 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000717 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000718 // We found one. The addressing mode tells us the max displacement
719 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000720
Evan Chenga8e29892007-01-19 07:51:42 +0000721 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000722 unsigned Bits = 0;
723 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000724 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000725 bool IsSoImm = false;
726
727 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000728 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000729 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000730
731 // Taking the address of a CP entry.
732 case ARM::LEApcrel:
733 // This takes a SoImm, which is 8 bit immediate rotated. We'll
734 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000735 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000736 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000737 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000738 Scale = 4;
739 NegOk = true;
740 IsSoImm = true;
741 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000742 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000743 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000744 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000745 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000746 case ARM::tLEApcrel:
747 Bits = 8;
748 Scale = 4;
749 break;
750
Jim Grosbach3e556122010-10-26 22:37:02 +0000751 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000752 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000753 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000754 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000755 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000756 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000757
758 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000759 Bits = 8;
760 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000761 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000762
Jim Grosbache5165492009-11-09 00:11:35 +0000763 case ARM::VLDRD:
764 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000765 Bits = 8;
766 Scale = 4; // +-(offset_8*4)
767 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000768 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000769 }
Evan Chengb43216e2007-02-01 10:16:15 +0000770
Evan Chenga8e29892007-01-19 07:51:42 +0000771 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000772 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000773 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000774 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000775 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000776
777 // Increment corresponding CPEntry reference count.
778 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
779 assert(CPE && "Cannot find a corresponding CPEntry!");
780 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000781
Evan Chenga8e29892007-01-19 07:51:42 +0000782 // Instructions can only use one CP entry, don't bother scanning the
783 // rest of the operands.
784 break;
785 }
786 }
Evan Chenga8e29892007-01-19 07:51:42 +0000787 }
788}
789
Jim Grosbach7a465252012-03-23 23:07:03 +0000790/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000791/// This function updates BBInfo directly.
Jim Grosbach7a465252012-03-23 23:07:03 +0000792void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000793 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
794 BBI.Size = 0;
795 BBI.Unalign = 0;
796 BBI.PostAlign = 0;
797
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000798 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
799 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000800 BBI.Size += TII->GetInstSizeInBytes(I);
801 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
802 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000803 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000804 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000805 // Also consider instructions that may be shrunk later.
806 else if (isThumb && mayOptimizeThumb2Instruction(I))
807 BBI.Unalign = 1;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000808 }
809
810 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000811 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000812 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000813 MBB->getParent()->EnsureAlignment(2);
814 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000815}
816
Jim Grosbach7a465252012-03-23 23:07:03 +0000817/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Chenga8e29892007-01-19 07:51:42 +0000818/// from the start of the function. This offset changes as stuff is moved
819/// around inside the function.
Jim Grosbach7a465252012-03-23 23:07:03 +0000820unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Chenga8e29892007-01-19 07:51:42 +0000821 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000822
Evan Chenga8e29892007-01-19 07:51:42 +0000823 // The offset is composed of two things: the sum of the sizes of all MBB's
824 // before this instruction's block, and the offset from the start of the block
825 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000826 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000827
828 // Sum instructions before MI in MBB.
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000829 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Chenga8e29892007-01-19 07:51:42 +0000830 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000831 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000832 }
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000833 return Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000834}
835
836/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
837/// ID.
838static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
839 const MachineBasicBlock *RHS) {
840 return LHS->getNumber() < RHS->getNumber();
841}
842
Jim Grosbach7a465252012-03-23 23:07:03 +0000843/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Chenga8e29892007-01-19 07:51:42 +0000844/// machine function, it upsets all of the block numbers. Renumber the blocks
845/// and update the arrays that parallel this numbering.
Jim Grosbach7a465252012-03-23 23:07:03 +0000846void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000847 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000848 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000849
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000850 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000851 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000852 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000853
854 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000855 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000856 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000857 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
858 CompareMBBNumbers);
859 WaterList.insert(IP, NewBB);
860}
861
862
863/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000864/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000865/// account for this change and returns the newly created block.
Jim Grosbach7a465252012-03-23 23:07:03 +0000866MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000867 MachineBasicBlock *OrigBB = MI->getParent();
868
869 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000870 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000871 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000872 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000873 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000874
Evan Chenga8e29892007-01-19 07:51:42 +0000875 // Splice the instructions starting with MI over to NewBB.
876 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000877
Evan Chenga8e29892007-01-19 07:51:42 +0000878 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000879 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000880 // There doesn't seem to be meaningful DebugInfo available; this doesn't
881 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000882 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000883 if (!isThumb)
884 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
885 else
886 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
887 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000888 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000889
Evan Chenga8e29892007-01-19 07:51:42 +0000890 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000891 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000892
Evan Chenga8e29892007-01-19 07:51:42 +0000893 // OrigBB branches to NewBB.
894 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000895
Evan Chenga8e29892007-01-19 07:51:42 +0000896 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +0000897 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000899 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000900
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000901 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000902 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000903 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000904
Bob Wilson84945262009-05-12 17:09:30 +0000905 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906 // available water after it (but not if it's already there, which happens
907 // when splitting before a conditional branch that is followed by an
908 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000909 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000910 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
911 CompareMBBNumbers);
912 MachineBasicBlock* WaterBB = *IP;
913 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000914 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000915 else
916 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000917 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000918
Dale Johannesen8086d582010-07-23 22:50:23 +0000919 // Figure out how large the OrigBB is. As the first half of the original
920 // block, it cannot contain a tablejump. The size includes
921 // the new jump we added. (It should be possible to do this without
922 // recounting everything, but it's very confusing, and this is rarely
923 // executed.)
Jim Grosbach7a465252012-03-23 23:07:03 +0000924 computeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000925
Dale Johannesen8086d582010-07-23 22:50:23 +0000926 // Figure out how large the NewMBB is. As the second half of the original
927 // block, it may contain a tablejump.
Jim Grosbach7a465252012-03-23 23:07:03 +0000928 computeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000929
Dale Johannesen99c49a42007-02-25 00:47:03 +0000930 // All BBOffsets following these blocks must be modified.
Jim Grosbach7a465252012-03-23 23:07:03 +0000931 adjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000932
933 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000934}
935
Jim Grosbach7a465252012-03-23 23:07:03 +0000936/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000937/// displacement computation. Update U.KnownAlignment to match its current
938/// basic block location.
Jim Grosbach7a465252012-03-23 23:07:03 +0000939unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
940 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000941 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
942 unsigned KnownBits = BBI.internalKnownBits();
943
944 // The value read from PC is offset from the actual instruction address.
945 UserOffset += (isThumb ? 4 : 8);
946
947 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
948 // Make sure U.getMaxDisp() returns a constrained range.
949 U.KnownAlignment = (KnownBits >= 2);
950
951 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
952 // purposes of the displacement computation; compensate for that here.
953 // For unknown alignments, getMaxDisp() constrains the range instead.
954 if (isThumb && U.KnownAlignment)
955 UserOffset &= ~3u;
956
957 return UserOffset;
958}
959
Jim Grosbach7a465252012-03-23 23:07:03 +0000960/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000961/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000962/// constant pool entry).
Jim Grosbach7a465252012-03-23 23:07:03 +0000963/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000964/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
965/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach7a465252012-03-23 23:07:03 +0000966bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000967 unsigned TrialOffset, unsigned MaxDisp,
968 bool NegativeOK, bool IsSoImm) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000969 if (UserOffset <= TrialOffset) {
970 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000971 if (TrialOffset - UserOffset <= MaxDisp)
972 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000973 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000974 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000975 if (UserOffset - TrialOffset <= MaxDisp)
976 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000977 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000978 }
979 return false;
980}
981
Jim Grosbach7a465252012-03-23 23:07:03 +0000982/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000983/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000984///
985/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach7a465252012-03-23 23:07:03 +0000986bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000987 MachineBasicBlock* Water, CPUser &U,
988 unsigned &Growth) {
989 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
990 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
991 unsigned NextBlockOffset, NextBlockAlignment;
992 MachineFunction::const_iterator NextBlock = Water;
993 if (++NextBlock == MF->end()) {
994 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
995 NextBlockAlignment = 0;
996 } else {
997 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
998 NextBlockAlignment = NextBlock->getAlignment();
999 }
1000 unsigned Size = U.CPEMI->getOperand(2).getImm();
1001 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001002
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001003 // The CPE may be able to hide in the alignment padding before the next
1004 // block. It may also cause more padding to be required if it is more aligned
1005 // that the next block.
1006 if (CPEEnd > NextBlockOffset) {
1007 Growth = CPEEnd - NextBlockOffset;
1008 // Compute the padding that would go at the end of the CPE to align the next
1009 // block.
1010 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1011
1012 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach7a465252012-03-23 23:07:03 +00001013 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001014 // in blocks between CPE and the user.
1015 if (CPEOffset < UserOffset)
1016 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1017 } else
1018 // CPE fits in existing padding.
1019 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001020
Jim Grosbach7a465252012-03-23 23:07:03 +00001021 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001022}
1023
Jim Grosbach7a465252012-03-23 23:07:03 +00001024/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001025/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001026bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001027 MachineInstr *CPEMI, unsigned MaxDisp,
1028 bool NegOk, bool DoDump) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001029 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng2021abe2007-02-01 01:09:47 +00001030
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001031 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001032 DEBUG({
1033 unsigned Block = MI->getParent()->getNumber();
1034 const BasicBlockInfo &BBI = BBInfo[Block];
1035 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1036 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001037 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001038 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001039 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1040 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1041 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001042 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001043 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001044
Jim Grosbach7a465252012-03-23 23:07:03 +00001045 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001046}
1047
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001048#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001049/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1050/// unconditionally branches to its only successor.
1051static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1052 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1053 return false;
1054
1055 MachineBasicBlock *Succ = *MBB->succ_begin();
1056 MachineBasicBlock *Pred = *MBB->pred_begin();
1057 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001058 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1059 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001060 return PredMI->getOperand(0).getMBB() == Succ;
1061 return false;
1062}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001063#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001064
Jim Grosbach7a465252012-03-23 23:07:03 +00001065void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001066 unsigned BBNum = BB->getNumber();
1067 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001068 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001069 // Include the alignment of the current block.
1070 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1071 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1072 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001073
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001074 // This is where block i begins. Stop if the offset is already correct,
1075 // and we have updated 2 blocks. This is the maximum number of blocks
1076 // changed before calling this function.
1077 if (i > BBNum + 2 &&
1078 BBInfo[i].Offset == Offset &&
1079 BBInfo[i].KnownBits == KnownBits)
1080 break;
1081
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001082 BBInfo[i].Offset = Offset;
1083 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001084 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001085}
1086
Jim Grosbach7a465252012-03-23 23:07:03 +00001087/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001088/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001089/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001090/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001091
Jim Grosbach7a465252012-03-23 23:07:03 +00001092bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1093 MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001094 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001095 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1096 assert(CPE && "Unexpected!");
1097 if (--CPE->RefCount == 0) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001098 removeDeadCPEMI(CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001099 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001100 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101 return true;
1102 }
1103 return false;
1104}
1105
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001106/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1107/// if not, see if an in-range clone of the CPE is in range, and if so,
1108/// change the data structures so the user references the clone. Returns:
1109/// 0 = no existing entry found
1110/// 1 = entry found, and there were no code insertions or deletions
1111/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach7a465252012-03-23 23:07:03 +00001112int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113{
1114 MachineInstr *UserMI = U.MI;
1115 MachineInstr *CPEMI = U.CPEMI;
1116
1117 // Check to see if the CPE is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001118 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1119 true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001120 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001121 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001122 }
1123
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001124 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001125 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001126 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1127 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1128 // We already tried this one
1129 if (CPEs[i].CPEMI == CPEMI)
1130 continue;
1131 // Removing CPEs can leave empty entries, skip
1132 if (CPEs[i].CPEMI == NULL)
1133 continue;
Jim Grosbach7a465252012-03-23 23:07:03 +00001134 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001135 U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001136 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001137 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001138 // Point the CPUser node to the replacement
1139 U.CPEMI = CPEs[i].CPEMI;
1140 // Change the CPI in the instruction operand to refer to the clone.
1141 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001142 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001143 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001144 break;
1145 }
1146 // Adjust the refcount of the clone...
1147 CPEs[i].RefCount++;
1148 // ...and the original. If we didn't remove the old entry, none of the
1149 // addresses changed, so we don't need another pass.
Jim Grosbach7a465252012-03-23 23:07:03 +00001150 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001151 }
1152 }
1153 return 0;
1154}
1155
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001156/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1157/// the specific unconditional branch instruction.
1158static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001159 switch (Opc) {
1160 case ARM::tB:
1161 return ((1<<10)-1)*2;
1162 case ARM::t2B:
1163 return ((1<<23)-1)*2;
1164 default:
1165 break;
1166 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001167
David Goodwin5e47a9a2009-06-30 18:04:13 +00001168 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001169}
1170
Jim Grosbach7a465252012-03-23 23:07:03 +00001171/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001173/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001174/// is set to the WaterList entry. For Thumb, prefer water that will not
1175/// introduce padding to water that will. To ensure that this pass
1176/// terminates, the CPE location for a particular CPUser is only allowed to
1177/// move to a lower address, so search backward from the end of the list and
1178/// prefer the first water that is in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001179bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001180 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001181 if (WaterList.empty())
1182 return false;
1183
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001184 unsigned BestGrowth = ~0u;
1185 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1186 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001187 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001188 // Check if water is in range and is either at a lower address than the
1189 // current "high water mark" or a new water block that was created since
1190 // the previous iteration by inserting an unconditional branch. In the
1191 // latter case, we want to allow resetting the high water mark back to
1192 // this new water since we haven't seen it before. Inserting branches
1193 // should be relatively uncommon and when it does happen, we want to be
1194 // sure to take advantage of it for all the CPEs near that block, so that
1195 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001196 unsigned Growth;
Jim Grosbach7a465252012-03-23 23:07:03 +00001197 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001198 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001199 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1200 // This is the least amount of required padding seen so far.
1201 BestGrowth = Growth;
1202 WaterIter = IP;
1203 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1204 << " Growth=" << Growth << '\n');
1205
1206 // Keep looking unless it is perfect.
1207 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001208 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001209 }
Bob Wilson3b757352009-10-12 19:04:03 +00001210 if (IP == B)
1211 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001212 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001213 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001214}
1215
Jim Grosbach7a465252012-03-23 23:07:03 +00001216/// createNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001217/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1218/// block is used if in range, and the conditional branch munged so control
1219/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001220/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001221/// block following which the new island can be inserted (the WaterList
1222/// is not adjusted).
Jim Grosbach7a465252012-03-23 23:07:03 +00001223void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001224 unsigned UserOffset,
1225 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001226 CPUser &U = CPUsers[CPUserIndex];
1227 MachineInstr *UserMI = U.MI;
1228 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001229 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001230 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001231 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001232
Bob Wilson36fa5322009-10-15 05:10:36 +00001233 // If the block does not end in an unconditional branch already, and if the
1234 // end of the block is within range, make new water there. (The addition
1235 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001236 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001237 if (BBHasFallthrough(UserMBB)) {
1238 // Size of branch to insert.
1239 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001240 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001241 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001242
Jim Grosbach7a465252012-03-23 23:07:03 +00001243 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001244 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1245 << format(", expected CPE offset %#x\n", CPEOffset));
1246 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1247 // Add an unconditional branch from UserMBB to fallthrough block. Record
1248 // it for branch lengthening; this new branch will not get out of range,
1249 // but if the preceding conditional branch is out of range, the targets
1250 // will be exchanged, and the altered branch may be out of range, so the
1251 // machinery has to know about it.
1252 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1253 if (!isThumb)
1254 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1255 else
1256 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1257 .addImm(ARMCC::AL).addReg(0);
1258 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1259 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1260 MaxDisp, false, UncondBr));
1261 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001262 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001263 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001264 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001265 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001266
1267 // What a big block. Find a place within the block to split it. This is a
1268 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1269 // entries are 4 bytes: if instruction I references island CPE, and
1270 // instruction I+1 references CPE', it will not work well to put CPE as far
1271 // forward as possible, since then CPE' cannot immediately follow it (that
1272 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1273 // need to create a new island. So, we make a first guess, then walk through
1274 // the instructions between the one currently being looked at and the
1275 // possible insertion point, and make sure any other instructions that
1276 // reference CPEs will be able to use the same island area; if not, we back
1277 // up the insertion point.
1278
1279 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001280 // point where we can add a 4-byte branch instruction, and then align to
1281 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001282 unsigned LogAlign = MF->getAlignment();
1283 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1284 unsigned KnownBits = UserBBI.internalKnownBits();
1285 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001286 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001287 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1288 BaseInsertOffset));
1289
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001290 // The 4 in the following is for the unconditional branch we'll be inserting
1291 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach7a465252012-03-23 23:07:03 +00001292 // inside isOffsetInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001293 BaseInsertOffset -= 4;
1294
1295 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1296 << " la=" << LogAlign
1297 << " kb=" << KnownBits
1298 << " up=" << UPad << '\n');
1299
1300 // This could point off the end of the block if we've already got constant
1301 // pool entries following this block; only the last one is in the water list.
1302 // Back past any possible branches (allow for a conditional and a maximally
1303 // long unconditional).
Jakob Stoklund Olesen9b10dae2012-04-28 06:21:38 +00001304 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1305 BaseInsertOffset = UserBBI.postOffset() - UPad - 8;
1306 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1307 }
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001308 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001309 CPEMI->getOperand(2).getImm();
1310 MachineBasicBlock::iterator MI = UserMI;
1311 ++MI;
1312 unsigned CPUIndex = CPUserIndex+1;
1313 unsigned NumCPUsers = CPUsers.size();
1314 MachineInstr *LastIT = 0;
1315 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1316 Offset < BaseInsertOffset;
1317 Offset += TII->GetInstSizeInBytes(MI),
1318 MI = llvm::next(MI)) {
Jakob Stoklund Olesen9b10dae2012-04-28 06:21:38 +00001319 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001320 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1321 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach7a465252012-03-23 23:07:03 +00001322 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001323 // Shift intertion point by one unit of alignment so it is within reach.
1324 BaseInsertOffset -= 1u << LogAlign;
1325 EndInsertOffset -= 1u << LogAlign;
1326 }
1327 // This is overly conservative, as we don't account for CPEMIs being
1328 // reused within the block, but it doesn't matter much. Also assume CPEs
1329 // are added in order with alignment padding. We may eventually be able
1330 // to pack the aligned CPEs better.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001331 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001332 CPUIndex++;
1333 }
1334
1335 // Remember the last IT instruction.
1336 if (MI->getOpcode() == ARM::t2IT)
1337 LastIT = MI;
1338 }
1339
1340 --MI;
1341
1342 // Avoid splitting an IT block.
1343 if (LastIT) {
1344 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001345 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001346 if (CC != ARMCC::AL)
1347 MI = LastIT;
1348 }
Jim Grosbach7a465252012-03-23 23:07:03 +00001349 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001350}
1351
Jim Grosbach7a465252012-03-23 23:07:03 +00001352/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001353/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001354/// place in-range. Return true if we changed any addresses (thus must run
1355/// another pass of branch lengthening), false otherwise.
Jim Grosbach7a465252012-03-23 23:07:03 +00001356bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001357 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001358 MachineInstr *UserMI = U.MI;
1359 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001360 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001361 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001362 // Compute this only once, it's expensive.
Jim Grosbach7a465252012-03-23 23:07:03 +00001363 unsigned UserOffset = getUserOffset(U);
Evan Cheng768c9f72007-04-27 08:14:15 +00001364
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001365 // See if the current entry is within range, or there is a clone of it
1366 // in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001367 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001368 if (result==1) return false;
1369 else if (result==2) return true;
1370
1371 // No existing clone of this CPE is within range.
1372 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001373 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001374
Bob Wilsonf98032e2009-10-12 21:23:15 +00001375 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001376 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001377 MachineBasicBlock *NewMBB;
1378 water_iterator IP;
Jim Grosbach7a465252012-03-23 23:07:03 +00001379 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001380 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001381 MachineBasicBlock *WaterBB = *IP;
1382
1383 // If the original WaterList entry was "new water" on this iteration,
1384 // propagate that to the new island. This is just keeping NewWaterList
1385 // updated to match the WaterList, which will be updated below.
1386 if (NewWaterList.count(WaterBB)) {
1387 NewWaterList.erase(WaterBB);
1388 NewWaterList.insert(NewIsland);
1389 }
1390 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001391 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001392
1393 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001394 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001395 DEBUG(dbgs() << "No water found\n");
Jim Grosbach7a465252012-03-23 23:07:03 +00001396 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001397
Jim Grosbach7a465252012-03-23 23:07:03 +00001398 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilsonb9239532009-10-15 20:49:47 +00001399 // called while handling branches so that the water will be seen on the
1400 // next iteration for constant pools, but in this context, we don't want
1401 // it. Check for this so it will be removed from the WaterList.
1402 // Also remove any entry from NewWaterList.
1403 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1404 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1405 if (IP != WaterList.end())
1406 NewWaterList.erase(WaterBB);
1407
1408 // We are adding new water. Update NewWaterList.
1409 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001410 }
1411
Bob Wilsonb9239532009-10-15 20:49:47 +00001412 // Remove the original WaterList entry; we want subsequent insertions in
1413 // this vicinity to go after the one we're about to insert. This
1414 // considerably reduces the number of times we have to move the same CPE
1415 // more than once and is also important to ensure the algorithm terminates.
1416 if (IP != WaterList.end())
1417 WaterList.erase(IP);
1418
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001419 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001420 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001421
1422 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +00001423 updateForInsertedWaterBlock(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001424
1425 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach7a465252012-03-23 23:07:03 +00001426 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001427
1428 // Now that we have an island to add the CPE to, clone the original CPE and
1429 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001430 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001431 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001432 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001433 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001434 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001435
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001436 // Mark the basic block as aligned as required by the const-pool entry.
1437 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001438
Evan Chenga8e29892007-01-19 07:51:42 +00001439 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001440 BBInfo[NewIsland->getNumber()].Size += Size;
Jim Grosbach7a465252012-03-23 23:07:03 +00001441 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001442
Evan Chenga8e29892007-01-19 07:51:42 +00001443 // Finally, change the CPI in the instruction operand to be ID.
1444 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001445 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001446 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001447 break;
1448 }
Bob Wilson84945262009-05-12 17:09:30 +00001449
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001450 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001451 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001452
Evan Chenga8e29892007-01-19 07:51:42 +00001453 return true;
1454}
1455
Jim Grosbach7a465252012-03-23 23:07:03 +00001456/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Chenged884f32007-04-03 23:39:48 +00001457/// sizes and offsets of impacted basic blocks.
Jim Grosbach7a465252012-03-23 23:07:03 +00001458void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Chenged884f32007-04-03 23:39:48 +00001459 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001460 unsigned Size = CPEMI->getOperand(2).getImm();
1461 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001462 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001463 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001464 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001465 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001466
1467 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1468 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001469 } else
1470 // Entries are sorted by descending alignment, so realign from the front.
1471 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1472
Jim Grosbach7a465252012-03-23 23:07:03 +00001473 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001474 // An island has only one predecessor BB and one successor BB. Check if
1475 // this BB's predecessor jumps directly to this BB's successor. This
1476 // shouldn't happen currently.
1477 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1478 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001479}
1480
Jim Grosbach7a465252012-03-23 23:07:03 +00001481/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Chenged884f32007-04-03 23:39:48 +00001482/// are zero.
Jim Grosbach7a465252012-03-23 23:07:03 +00001483bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Chenged884f32007-04-03 23:39:48 +00001484 unsigned MadeChange = false;
1485 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1486 std::vector<CPEntry> &CPEs = CPEntries[i];
1487 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1488 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001489 removeDeadCPEMI(CPEs[j].CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001490 CPEs[j].CPEMI = NULL;
1491 MadeChange = true;
1492 }
1493 }
Bob Wilson84945262009-05-12 17:09:30 +00001494 }
Evan Chenged884f32007-04-03 23:39:48 +00001495 return MadeChange;
1496}
1497
Jim Grosbach7a465252012-03-23 23:07:03 +00001498/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001499/// specific BB can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001500bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Chengc0dbec72007-01-31 19:57:44 +00001501 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001502 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach7a465252012-03-23 23:07:03 +00001503 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001504 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001505
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001506 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001507 << " from BB#" << MI->getParent()->getNumber()
1508 << " max delta=" << MaxDisp
Jim Grosbach7a465252012-03-23 23:07:03 +00001509 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattner705e07f2009-08-23 03:41:05 +00001510 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001511
Dale Johannesen8593e412007-04-29 19:19:30 +00001512 if (BrOffset <= DestOffset) {
1513 // Branch before the Dest.
1514 if (DestOffset-BrOffset <= MaxDisp)
1515 return true;
1516 } else {
1517 if (BrOffset-DestOffset <= MaxDisp)
1518 return true;
1519 }
1520 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001521}
1522
Jim Grosbach7a465252012-03-23 23:07:03 +00001523/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001524/// away to fit in its displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001525bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001526 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001527 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001528
Evan Chengc0dbec72007-01-31 19:57:44 +00001529 // Check to see if the DestBB is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001530 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001531 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001532
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001533 if (!Br.isCond)
Jim Grosbach7a465252012-03-23 23:07:03 +00001534 return fixupUnconditionalBr(Br);
1535 return fixupConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001536}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001537
Jim Grosbach7a465252012-03-23 23:07:03 +00001538/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001539/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001540/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001541/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001542bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001543ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001544 MachineInstr *MI = Br.MI;
1545 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001546 if (!isThumb1)
Jim Grosbach7a465252012-03-23 23:07:03 +00001547 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001548
1549 // Use BL to implement far jump.
1550 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001551 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001552 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001553 adjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001554 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001555 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001556
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001557 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001558
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001559 return true;
1560}
1561
Jim Grosbach7a465252012-03-23 23:07:03 +00001562/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001563/// far away to fit in its displacement field. It is converted to an inverse
1564/// conditional branch + an unconditional branch to the destination.
1565bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001566ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001567 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001568 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001569
Bob Wilson39bf0512009-05-12 17:35:29 +00001570 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001571 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001572 // blt L1
1573 // =>
1574 // bge L2
1575 // b L1
1576 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001577 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001578 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001579 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001580
1581 // If the branch is at the end of its MBB and that has a fall-through block,
1582 // direct the updated conditional branch to the fall-through block. Otherwise,
1583 // split the MBB before the next instruction.
1584 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001585 MachineInstr *BMI = &MBB->back();
1586 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001587
Dan Gohmanfe601042010-06-22 15:08:57 +00001588 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001589 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001590 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001591 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001592 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001593 // condition and swap destinations:
1594 // beq L1
1595 // b L2
1596 // =>
1597 // bne L2
1598 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001599 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001600 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001601 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001602 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001603 BMI->getOperand(0).setMBB(DestBB);
1604 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001605 MI->getOperand(1).setImm(CC);
1606 return true;
1607 }
1608 }
1609 }
1610
1611 if (NeedSplit) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001612 splitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001613 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001614 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001615 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001616 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001617 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001618 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001619 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001620 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001621
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001622 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001623 << " also invert condition and change dest. to BB#"
1624 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001625
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001626 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001627 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001628 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001629 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001630 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001631 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001632 if (isThumb)
1633 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1634 .addImm(ARMCC::AL).addReg(0);
1635 else
1636 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001637 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001638 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001639 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001640
1641 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001642 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001643 MI->eraseFromParent();
Jim Grosbach7a465252012-03-23 23:07:03 +00001644 adjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001645 return true;
1646}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001647
Jim Grosbach7a465252012-03-23 23:07:03 +00001648/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001649/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1650/// to do this if tBfar is not used.
Jim Grosbach7a465252012-03-23 23:07:03 +00001651bool ARMConstantIslands::undoLRSpillRestore() {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001652 bool MadeChange = false;
1653 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1654 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001655 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001656 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001657 MI->getOperand(2).getReg() == ARM::PC &&
1658 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001659 // Create the new insn and copy the predicate from the old.
1660 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1661 .addOperand(MI->getOperand(0))
1662 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001663 MI->eraseFromParent();
1664 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001665 }
1666 }
1667 return MadeChange;
1668}
Evan Cheng5657c012009-07-29 02:18:14 +00001669
Jim Grosbach7a465252012-03-23 23:07:03 +00001670// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001671// below may shrink MI.
1672bool
1673ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1674 switch(MI->getOpcode()) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001675 // optimizeThumb2Instructions.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001676 case ARM::t2LEApcrel:
1677 case ARM::t2LDRpci:
Jim Grosbach7a465252012-03-23 23:07:03 +00001678 // optimizeThumb2Branches.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001679 case ARM::t2B:
1680 case ARM::t2Bcc:
1681 case ARM::tBcc:
Jim Grosbach7a465252012-03-23 23:07:03 +00001682 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001683 case ARM::t2BR_JT:
1684 return true;
1685 }
1686 return false;
1687}
1688
Jim Grosbach7a465252012-03-23 23:07:03 +00001689bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001690 bool MadeChange = false;
1691
1692 // Shrink ADR and LDR from constantpool.
1693 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1694 CPUser &U = CPUsers[i];
1695 unsigned Opcode = U.MI->getOpcode();
1696 unsigned NewOpc = 0;
1697 unsigned Scale = 1;
1698 unsigned Bits = 0;
1699 switch (Opcode) {
1700 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001701 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001702 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1703 NewOpc = ARM::tLEApcrel;
1704 Bits = 8;
1705 Scale = 4;
1706 }
1707 break;
1708 case ARM::t2LDRpci:
1709 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1710 NewOpc = ARM::tLDRpci;
1711 Bits = 8;
1712 Scale = 4;
1713 }
1714 break;
1715 }
1716
1717 if (!NewOpc)
1718 continue;
1719
Jim Grosbach7a465252012-03-23 23:07:03 +00001720 unsigned UserOffset = getUserOffset(U);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001721 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001722
1723 // Be conservative with inline asm.
1724 if (!U.KnownAlignment)
1725 MaxOffs -= 2;
1726
Evan Chenga1efbbd2009-08-14 00:32:16 +00001727 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach7a465252012-03-23 23:07:03 +00001728 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001729 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001730 U.MI->setDesc(TII->get(NewOpc));
1731 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001732 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001733 adjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001734 ++NumT2CPShrunk;
1735 MadeChange = true;
1736 }
1737 }
1738
Jim Grosbach7a465252012-03-23 23:07:03 +00001739 MadeChange |= optimizeThumb2Branches();
1740 MadeChange |= optimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001741 return MadeChange;
1742}
1743
Jim Grosbach7a465252012-03-23 23:07:03 +00001744bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001745 bool MadeChange = false;
1746
1747 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1748 ImmBranch &Br = ImmBranches[i];
1749 unsigned Opcode = Br.MI->getOpcode();
1750 unsigned NewOpc = 0;
1751 unsigned Scale = 1;
1752 unsigned Bits = 0;
1753 switch (Opcode) {
1754 default: break;
1755 case ARM::t2B:
1756 NewOpc = ARM::tB;
1757 Bits = 11;
1758 Scale = 2;
1759 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001760 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001761 NewOpc = ARM::tBcc;
1762 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001763 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001764 break;
1765 }
Evan Chengde17fb62009-10-31 23:46:45 +00001766 }
1767 if (NewOpc) {
1768 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1769 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001770 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001771 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Chengde17fb62009-10-31 23:46:45 +00001772 Br.MI->setDesc(TII->get(NewOpc));
1773 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001774 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001775 adjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001776 ++NumT2BrShrunk;
1777 MadeChange = true;
1778 }
1779 }
1780
1781 Opcode = Br.MI->getOpcode();
1782 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001783 continue;
1784
Evan Chengbfe8afa2012-01-14 01:53:46 +00001785 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1786 // so this transformation is not safe.
1787 if (!Br.MI->killsRegister(ARM::CPSR))
1788 continue;
1789
Evan Chengde17fb62009-10-31 23:46:45 +00001790 NewOpc = 0;
1791 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001792 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Chengde17fb62009-10-31 23:46:45 +00001793 if (Pred == ARMCC::EQ)
1794 NewOpc = ARM::tCBZ;
1795 else if (Pred == ARMCC::NE)
1796 NewOpc = ARM::tCBNZ;
1797 if (!NewOpc)
1798 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001799 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001800 // Check if the distance is within 126. Subtract starting offset by 2
1801 // because the cmp will be eliminated.
Jim Grosbach7a465252012-03-23 23:07:03 +00001802 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001803 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001804 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001805 MachineBasicBlock::iterator CmpMI = Br.MI;
1806 if (CmpMI != Br.MI->getParent()->begin()) {
1807 --CmpMI;
1808 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1809 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperc89c7442012-03-27 07:21:54 +00001810 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng0539c152011-04-01 22:09:28 +00001811 if (Pred == ARMCC::AL &&
1812 CmpMI->getOperand(1).getImm() == 0 &&
1813 isARMLowRegister(Reg)) {
1814 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001815 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng0539c152011-04-01 22:09:28 +00001816 MachineInstr *NewBR =
1817 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1818 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1819 CmpMI->eraseFromParent();
1820 Br.MI->eraseFromParent();
1821 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001822 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001823 adjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001824 ++NumCBZ;
1825 MadeChange = true;
1826 }
Evan Chengde17fb62009-10-31 23:46:45 +00001827 }
1828 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001829 }
1830 }
1831
1832 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001833}
1834
Jim Grosbach7a465252012-03-23 23:07:03 +00001835/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chenga1efbbd2009-08-14 00:32:16 +00001836/// jumptables when it's possible.
Jim Grosbach7a465252012-03-23 23:07:03 +00001837bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001838 bool MadeChange = false;
1839
1840 // FIXME: After the tables are shrunk, can we get rid some of the
1841 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001842 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001843 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001844
Evan Cheng5657c012009-07-29 02:18:14 +00001845 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1846 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1847 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001848 const MCInstrDesc &MCID = MI->getDesc();
1849 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001850 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001851 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1852 unsigned JTI = JTOP.getIndex();
1853 assert(JTI < JT.size());
1854
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001855 bool ByteOk = true;
1856 bool HalfWordOk = true;
Jim Grosbach7a465252012-03-23 23:07:03 +00001857 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach80697d12009-11-12 17:25:07 +00001858 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001859 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1860 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001861 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001862 // Negative offset is not ok. FIXME: We should change BB layout to make
1863 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001864 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001865 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001866 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001867 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001868 HalfWordOk = false;
1869 if (!ByteOk && !HalfWordOk)
1870 break;
1871 }
1872
1873 if (ByteOk || HalfWordOk) {
1874 MachineBasicBlock *MBB = MI->getParent();
1875 unsigned BaseReg = MI->getOperand(0).getReg();
1876 bool BaseRegKill = MI->getOperand(0).isKill();
1877 if (!BaseRegKill)
1878 continue;
1879 unsigned IdxReg = MI->getOperand(1).getReg();
1880 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001881
1882 // Scan backwards to find the instruction that defines the base
1883 // register. Due to post-RA scheduling, we can't count on it
1884 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001885 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001886 MachineBasicBlock::iterator B = MBB->begin();
1887 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1888 --PrevI;
1889
1890 // If for some reason we didn't find it, we can't do anything, so
1891 // just skip this one.
1892 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001893 continue;
1894
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001895 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001896 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001897 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001898 // Make sure it only defines the base register and kills any uses
1899 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001900 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1901 const MachineOperand &MO = AddrMI->getOperand(k);
1902 if (!MO.isReg() || !MO.getReg())
1903 continue;
1904 if (MO.isDef() && MO.getReg() != BaseReg) {
1905 OptOk = false;
1906 break;
1907 }
1908 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1909 OptOk = false;
1910 break;
1911 }
1912 }
1913 if (!OptOk)
1914 continue;
1915
Owen Anderson6b8719f2010-12-13 22:51:08 +00001916 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001917 // that gave us the initial base register definition.
1918 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1919 ;
1920
Owen Anderson6b8719f2010-12-13 22:51:08 +00001921 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001922 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001923 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001924 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001925 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001926 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001927 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001928
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001929 if (!OptOk)
1930 continue;
1931
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001932 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1933 << " lea: " << *LeaMI);
Jim Grosbachd092a872010-11-29 21:28:32 +00001934 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001935 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1936 .addReg(IdxReg, getKillRegState(IdxRegKill))
1937 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1938 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001939 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001940 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1941 // is 2-byte aligned. For now, asm printer will fix it up.
1942 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1943 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1944 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1945 OrigSize += TII->GetInstSizeInBytes(MI);
1946
1947 AddrMI->eraseFromParent();
1948 LeaMI->eraseFromParent();
1949 MI->eraseFromParent();
1950
1951 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001952 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001953 adjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001954
1955 ++NumTBs;
1956 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001957 }
1958 }
1959
1960 return MadeChange;
1961}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001962
Jim Grosbach7a465252012-03-23 23:07:03 +00001963/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach9249efe2009-11-16 18:55:47 +00001964/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach7a465252012-03-23 23:07:03 +00001965bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001966 bool MadeChange = false;
1967
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001968 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001969 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001970
Jim Grosbach80697d12009-11-12 17:25:07 +00001971 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1972 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1973 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001974 const MCInstrDesc &MCID = MI->getDesc();
1975 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001976 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001977 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1978 unsigned JTI = JTOP.getIndex();
1979 assert(JTI < JT.size());
1980
1981 // We prefer if target blocks for the jump table come after the jump
1982 // instruction so we can use TB[BH]. Loop through the target blocks
1983 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001984 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001985 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1986 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1987 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001988 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001989
Jim Grosbach08cbda52009-11-16 18:58:52 +00001990 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001991 // The destination precedes the switch. Try to move the block forward
1992 // so we have a positive offset.
1993 MachineBasicBlock *NewBB =
Jim Grosbach7a465252012-03-23 23:07:03 +00001994 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach80697d12009-11-12 17:25:07 +00001995 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001996 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001997 MadeChange = true;
1998 }
1999 }
2000 }
2001
2002 return MadeChange;
2003}
2004
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002005MachineBasicBlock *ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +00002006adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach03e2d442010-07-07 22:53:35 +00002007 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00002008 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00002009 // table that branches back to the actual target. This is a very simple
2010 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00002011 MachineBasicBlock *TBB = 0, *FBB = 0;
2012 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002013 SmallVector<MachineOperand, 4> CondPrior;
2014 MachineFunction::iterator BBi = BB;
2015 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002016
Jim Grosbachca215e72009-11-16 17:10:56 +00002017 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002018 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00002019
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002020 // If the block ends in an unconditional branch, move it. The prior block
2021 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00002022 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002023 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002024 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002025 BB->moveAfter(JTBB);
2026 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002027 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00002028 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002029 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00002030 ++NumJTMoved;
2031 return NULL;
2032 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002033
2034 // Create a new MBB for the code after the jump BB.
2035 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002036 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002037 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002038 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002039
2040 // Add an unconditional branch from NewBB to BB.
2041 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2042 // correspond directly to anything in the source.
2043 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00002044 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2045 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002046
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002047 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002048 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002049
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002050 // Update the CFG.
2051 NewBB->addSuccessor(BB);
2052 JTBB->removeSuccessor(BB);
2053 JTBB->addSuccessor(NewBB);
2054
Jim Grosbach80697d12009-11-12 17:25:07 +00002055 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002056 return NewBB;
2057}