blob: 53433354df5aa4f18c17d38f686ead6bcb87759b [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 Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000020#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.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 Olesen540c6d92011-12-08 00:55:02 +000055/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
56/// add padding such that:
57///
58/// 1. The result is aligned to 1 << LogAlign.
59///
60/// 2. No other value of the unknown bits would require more padding.
61///
62/// This may add more padding than is required to satisfy just one of the
63/// constraints. It is necessary to compute alignment this way to guarantee
64/// that we don't underestimate the padding before an aligned block. If the
65/// real padding before a block is larger than we think, constant pool entries
66/// may go out of range.
67static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
68 unsigned KnownBits) {
69 // Add the worst possible padding that the unknown bits could cause.
70 if (KnownBits < LogAlign)
71 Offset += (1u << LogAlign) - (1u << KnownBits);
72
73 // Then align the result.
74 return RoundUpToAlignment(Offset, 1u << LogAlign);
75}
76
Evan Chenga8e29892007-01-19 07:51:42 +000077namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000078 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000079 /// requires constant pool entries to be scattered among the instructions
80 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000081 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000082 /// special instructions.
83 ///
84 /// The terminology used in this pass includes:
85 /// Islands - Clumps of constants placed in the function.
86 /// Water - Potential places where an island could be formed.
87 /// CPE - A constant pool entry that has been placed somewhere, which
88 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000089 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000090 /// BasicBlockInfo - Information about the offset and size of a single
91 /// basic block.
92 struct BasicBlockInfo {
93 /// Offset - Distance from the beginning of the function to the beginning
94 /// of this basic block.
95 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000096 /// The offset is always aligned as required by the basic block.
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
123 /// Compute the offset immediately following this block.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000124 unsigned postOffset() const {
125 unsigned PO = Offset + Size;
126 if (!PostAlign)
127 return PO;
128 // Add alignment padding from the terminator.
129 return WorstCaseAlign(PO, PostAlign, Unalign ? Unalign : KnownBits);
130 }
131
132 /// Compute the number of known low bits of postOffset. If this block
133 /// contains inline asm, the number of known bits drops to the
134 /// instruction alignment. An aligned terminator may increase the number
135 /// of know bits.
136 unsigned postKnownBits() const {
137 return std::max(PostAlign, Unalign ? Unalign : KnownBits);
138 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000139 };
140
141 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000142
Evan Chenga8e29892007-01-19 07:51:42 +0000143 /// WaterList - A sorted list of basic blocks where islands could be placed
144 /// (i.e. blocks that don't fall through to the following block, due
145 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000146 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000147
Bob Wilsonb9239532009-10-15 20:49:47 +0000148 /// NewWaterList - The subset of WaterList that was created since the
149 /// previous iteration by inserting unconditional branches.
150 SmallSet<MachineBasicBlock*, 4> NewWaterList;
151
Bob Wilson034de5f2009-10-12 18:52:13 +0000152 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
153
Evan Chenga8e29892007-01-19 07:51:42 +0000154 /// CPUser - One user of a constant pool, keeping the machine instruction
155 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000156 /// allowed from the instruction to the CP. The HighWaterMark records the
157 /// highest basic block where a new CPEntry can be placed. To ensure this
158 /// pass terminates, the CP entries are initially placed at the end of the
159 /// function and then move monotonically to lower addresses. The
160 /// exception to this rule is when the current CP entry for a particular
161 /// CPUser is out of range, but there is another CP entry for the same
162 /// constant value in range. We want to use the existing in-range CP
163 /// entry, but if it later moves out of range, the search for new water
164 /// should resume where it left off. The HighWaterMark is used to record
165 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000166 struct CPUser {
167 MachineInstr *MI;
168 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000169 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000170 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000171 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000172 bool IsSoImm;
173 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
174 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000175 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
176 HighWaterMark = CPEMI->getParent();
177 }
Evan Chenga8e29892007-01-19 07:51:42 +0000178 };
Bob Wilson84945262009-05-12 17:09:30 +0000179
Evan Chenga8e29892007-01-19 07:51:42 +0000180 /// CPUsers - Keep track of all of the machine instructions that use various
181 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000182 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000183
Evan Chengc99ef082007-02-09 20:54:44 +0000184 /// CPEntry - One per constant pool entry, keeping the machine instruction
185 /// pointer, the constpool index, and the number of CPUser's which
186 /// reference this entry.
187 struct CPEntry {
188 MachineInstr *CPEMI;
189 unsigned CPI;
190 unsigned RefCount;
191 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
192 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
193 };
194
195 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000196 /// instructions. For each original constpool index (i.e. those that
197 /// existed upon entry to this pass), it keeps a vector of entries.
198 /// Original elements are cloned as we go along; the clones are
199 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000200 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000201
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000202 /// ImmBranch - One per immediate branch, keeping the machine instruction
203 /// pointer, conditional or unconditional, the max displacement,
204 /// and (if isCond is true) the corresponding unconditional branch
205 /// opcode.
206 struct ImmBranch {
207 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000208 unsigned MaxDisp : 31;
209 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000210 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000211 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
212 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000213 };
214
Evan Cheng2706f972007-05-16 05:14:06 +0000215 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000216 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000217 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000218
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000219 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
220 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000221 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000222
Evan Cheng5657c012009-07-29 02:18:14 +0000223 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
224 SmallVector<MachineInstr*, 4> T2JumpTables;
225
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000226 /// HasFarJump - True if any far jump instruction has been emitted during
227 /// the branch fix up pass.
228 bool HasFarJump;
229
Chris Lattner20628752010-07-22 21:27:00 +0000230 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000231 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000232 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000233 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000234 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000235 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000236 public:
Devang Patel19974732007-05-03 01:11:54 +0000237 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000238 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000239
Evan Cheng5657c012009-07-29 02:18:14 +0000240 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000241
242 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000243 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000244 }
Bob Wilson84945262009-05-12 17:09:30 +0000245
Evan Chenga8e29892007-01-19 07:51:42 +0000246 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000247 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000248 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000249 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000250 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000251 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000252 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000253 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000254 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000255 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000256 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000257 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000258 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000259 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000260 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000261 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000262 void RemoveDeadCPEMI(MachineInstr *CPEMI);
263 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000264 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000265 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
266 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000267 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000268 CPUser &U);
Evan Chengc0dbec72007-01-31 19:57:44 +0000269 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000270 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
271 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
272 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000273 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000274 bool OptimizeThumb2Instructions(MachineFunction &MF);
275 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000276 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000277 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000278 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
279 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000280
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000281 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000282 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000283 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000284 void verify(MachineFunction &MF);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000285
286 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
287 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
288 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
289 const CPUser &U) {
290 return OffsetIsInRange(UserOffset, TrialOffset,
291 U.MaxDisp, U.NegOk, U.IsSoImm);
292 }
Evan Chenga8e29892007-01-19 07:51:42 +0000293 };
Devang Patel19974732007-05-03 01:11:54 +0000294 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000295}
296
Dale Johannesen8593e412007-04-29 19:19:30 +0000297/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000298void ARMConstantIslands::verify(MachineFunction &MF) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000299#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000300 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000301 MBBI != E; ++MBBI) {
302 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000303 unsigned Align = MBB->getAlignment();
304 unsigned MBBId = MBB->getNumber();
305 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
306 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000307 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000308 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
309 CPUser &U = CPUsers[i];
310 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000311 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
312 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
313 UserOffset - CPEOffset;
314 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000315 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000316#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000317}
318
319/// print block size and offset information - debugging
320void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000321 DEBUG({
322 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
323 const BasicBlockInfo &BBI = BBInfo[J];
324 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
325 << " kb=" << unsigned(BBI.KnownBits)
326 << " ua=" << unsigned(BBI.Unalign)
327 << " pa=" << unsigned(BBI.PostAlign)
328 << format(" size=%#x\n", BBInfo[J].Size);
329 }
330 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000331}
332
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000333/// createARMConstantIslandPass - returns an instance of the constpool
334/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000335FunctionPass *llvm::createARMConstantIslandPass() {
336 return new ARMConstantIslands();
337}
338
Evan Cheng5657c012009-07-29 02:18:14 +0000339bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
340 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000341
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000342 DEBUG(dbgs() << "***** ARMConstantIslands: "
343 << MCP.getConstants().size() << " CP entries, aligned to "
344 << MCP.getConstantPoolAlignment() << " bytes *****\n");
345
Chris Lattner20628752010-07-22 21:27:00 +0000346 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000347 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000348 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
349
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000350 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000351 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000352 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000353
354 HasFarJump = false;
355
Evan Chenga8e29892007-01-19 07:51:42 +0000356 // Renumber all of the machine basic blocks in the function, guaranteeing that
357 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000358 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000359
Jim Grosbach80697d12009-11-12 17:25:07 +0000360 // Try to reorder and otherwise adjust the block layout to make good use
361 // of the TB[BH] instructions.
362 bool MadeChange = false;
363 if (isThumb2 && AdjustJumpTableBlocks) {
364 JumpTableFunctionScan(MF);
365 MadeChange |= ReorderThumb2JumpTables(MF);
366 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000367 T2JumpTables.clear();
368 // Blocks may have shifted around. Keep the numbering up to date.
369 MF.RenumberBlocks();
370 }
371
Evan Chengd26b14c2009-07-31 18:28:05 +0000372 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000373 // This is so we can keep exact track of where the alignment padding goes.
374
Chris Lattner7d7dab02010-01-27 23:37:36 +0000375 // ARM and Thumb2 functions need to be 4-byte aligned.
376 if (!isThumb1)
377 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000378
Evan Chenga8e29892007-01-19 07:51:42 +0000379 // Perform the initial placement of the constant pool entries. To start with,
380 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000381 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000382 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000383 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000384 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000385 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000386 }
Bob Wilson84945262009-05-12 17:09:30 +0000387
Evan Chenga8e29892007-01-19 07:51:42 +0000388 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000389 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000390
Evan Chenga8e29892007-01-19 07:51:42 +0000391 // Do the initial scan of the function, building up information about the
392 // sizes of each block, the location of all the water, and finding all of the
393 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000394 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000395 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000396 DEBUG(dumpBBs());
397
Bob Wilson84945262009-05-12 17:09:30 +0000398
Evan Chenged884f32007-04-03 23:39:48 +0000399 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000400 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000401
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000402 // Iteratively place constant pool entries and fix up branches until there
403 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000404 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000405 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000406 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000407 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000408 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000409 CPChange |= HandleConstantPoolUser(MF, i);
410 if (CPChange && ++NoCPIters > 30)
411 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000412 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000413
Bob Wilsonb9239532009-10-15 20:49:47 +0000414 // Clear NewWaterList now. If we split a block for branches, it should
415 // appear as "new water" for the next iteration of constant pool placement.
416 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000417
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000418 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000419 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000420 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000421 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
422 if (BRChange && ++NoBRIters > 30)
423 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000424 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000425
426 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000427 break;
428 MadeChange = true;
429 }
Evan Chenged884f32007-04-03 23:39:48 +0000430
Evan Chenga1efbbd2009-08-14 00:32:16 +0000431 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000432 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000433 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000434
Dale Johannesen8593e412007-04-29 19:19:30 +0000435 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000436 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000437
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000438 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
439 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000440 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000441 MadeChange |= UndoLRSpillRestore();
442
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000443 // Save the mapping between original and cloned constpool entries.
444 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
445 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
446 const CPEntry & CPE = CPEntries[i][j];
447 AFI->recordCPEClone(i, CPE.CPI);
448 }
449 }
450
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000451 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000452
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000453 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000454 WaterList.clear();
455 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000456 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000457 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000458 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000459 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000460
461 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000462}
463
464/// DoInitialPlacement - Perform the initial placement of the constant pool
465/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000466void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000467 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000468 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000469 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
470 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000471
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000472 // Mark the basic block as 4-byte aligned as required by the const-pool.
473 BB->setAlignment(2);
474
Evan Chenga8e29892007-01-19 07:51:42 +0000475 // Add all of the constants from the constant pool to the end block, use an
476 // identity mapping of CPI's to CPE's.
477 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000478 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000479
Evan Cheng5657c012009-07-29 02:18:14 +0000480 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000481 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000482 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000483 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
484 // we would have to pad them out or something so that instructions stay
485 // aligned.
486 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
487 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000488 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
489 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000490 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000491
492 // Add a new CPEntry, but no corresponding CPUser yet.
493 std::vector<CPEntry> CPEs;
494 CPEs.push_back(CPEntry(CPEMI, i));
495 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000496 ++NumCPEs;
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000497 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function as #" << i
Chris Lattner893e1c92009-08-23 06:49:22 +0000498 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000499 }
500}
501
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000502/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000503/// into the block immediately after it.
504static bool BBHasFallthrough(MachineBasicBlock *MBB) {
505 // Get the next machine basic block in the function.
506 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000507 // Can't fall off end of function.
508 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000509 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000510
Chris Lattner7896c9f2009-12-03 00:50:42 +0000511 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000512 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
513 E = MBB->succ_end(); I != E; ++I)
514 if (*I == NextBB)
515 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000516
Evan Chenga8e29892007-01-19 07:51:42 +0000517 return false;
518}
519
Evan Chengc99ef082007-02-09 20:54:44 +0000520/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
521/// look up the corresponding CPEntry.
522ARMConstantIslands::CPEntry
523*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
524 const MachineInstr *CPEMI) {
525 std::vector<CPEntry> &CPEs = CPEntries[CPI];
526 // Number of entries per constpool index should be small, just do a
527 // linear search.
528 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
529 if (CPEs[i].CPEMI == CPEMI)
530 return &CPEs[i];
531 }
532 return NULL;
533}
534
Jim Grosbach80697d12009-11-12 17:25:07 +0000535/// JumpTableFunctionScan - Do a scan of the function, building up
536/// information about the sizes of each block and the locations of all
537/// the jump tables.
538void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000539 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
540 MBBI != E; ++MBBI) {
541 MachineBasicBlock &MBB = *MBBI;
542
Jim Grosbach80697d12009-11-12 17:25:07 +0000543 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000544 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000545 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000546 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000547 }
548}
549
Evan Chenga8e29892007-01-19 07:51:42 +0000550/// InitialFunctionScan - Do the initial scan of the function, building up
551/// information about the sizes of each block, the location of all the water,
552/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000553void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000554 const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000555 BBInfo.clear();
556 BBInfo.resize(MF.getNumBlockIDs());
557
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000558 // First thing, compute the size of all basic blocks, and see if the function
559 // has any inline assembly in it. If so, we have to be conservative about
560 // alignment assumptions, as we don't know for sure the size of any
561 // instructions in the inline assembly.
562 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
563 ComputeBlockSize(I);
564
565 // The known bits of the entry block offset are determined by the function
566 // alignment.
567 BBInfo.front().KnownBits = MF.getAlignment();
568
569 // Compute block offsets and known bits.
570 AdjustBBOffsetsAfter(MF.begin());
571
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000572 // Now go back through the instructions and build up our data structures.
Evan Cheng5657c012009-07-29 02:18:14 +0000573 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000574 MBBI != E; ++MBBI) {
575 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000576
Evan Chenga8e29892007-01-19 07:51:42 +0000577 // If this block doesn't fall through into the next MBB, then this is
578 // 'water' that a constant pool island could be placed.
579 if (!BBHasFallthrough(&MBB))
580 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000581
Evan Chenga8e29892007-01-19 07:51:42 +0000582 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
583 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000584 if (I->isDebugValue())
585 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000586
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000587 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000588 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000589 bool isCond = false;
590 unsigned Bits = 0;
591 unsigned Scale = 1;
592 int UOpc = Opc;
593 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000594 default:
595 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000596 case ARM::t2BR_JT:
597 T2JumpTables.push_back(I);
598 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000599 case ARM::Bcc:
600 isCond = true;
601 UOpc = ARM::B;
602 // Fallthrough
603 case ARM::B:
604 Bits = 24;
605 Scale = 4;
606 break;
607 case ARM::tBcc:
608 isCond = true;
609 UOpc = ARM::tB;
610 Bits = 8;
611 Scale = 2;
612 break;
613 case ARM::tB:
614 Bits = 11;
615 Scale = 2;
616 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000617 case ARM::t2Bcc:
618 isCond = true;
619 UOpc = ARM::t2B;
620 Bits = 20;
621 Scale = 2;
622 break;
623 case ARM::t2B:
624 Bits = 24;
625 Scale = 2;
626 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000627 }
Evan Chengb43216e2007-02-01 10:16:15 +0000628
629 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000630 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000631 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000632 }
633
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000634 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
635 PushPopMIs.push_back(I);
636
Evan Chengd3d9d662009-07-23 18:27:47 +0000637 if (Opc == ARM::CONSTPOOL_ENTRY)
638 continue;
639
Evan Chenga8e29892007-01-19 07:51:42 +0000640 // Scan the instructions for constant pool operands.
641 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000642 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000643 // We found one. The addressing mode tells us the max displacement
644 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000645
Evan Chenga8e29892007-01-19 07:51:42 +0000646 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000647 unsigned Bits = 0;
648 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000649 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000650 bool IsSoImm = false;
651
652 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000653 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000654 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000655 break;
656
657 // Taking the address of a CP entry.
658 case ARM::LEApcrel:
659 // This takes a SoImm, which is 8 bit immediate rotated. We'll
660 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000661 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000662 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000663 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000664 Scale = 4;
665 NegOk = true;
666 IsSoImm = true;
667 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000668 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000669 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000670 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000671 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000672 case ARM::tLEApcrel:
673 Bits = 8;
674 Scale = 4;
675 break;
676
Jim Grosbach3e556122010-10-26 22:37:02 +0000677 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000678 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000679 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000680 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000681 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000682 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000683
684 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000685 Bits = 8;
686 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000687 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000688
Jim Grosbache5165492009-11-09 00:11:35 +0000689 case ARM::VLDRD:
690 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000691 Bits = 8;
692 Scale = 4; // +-(offset_8*4)
693 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000694 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000695 }
Evan Chengb43216e2007-02-01 10:16:15 +0000696
Evan Chenga8e29892007-01-19 07:51:42 +0000697 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000698 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000699 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000700 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000701 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000702
703 // Increment corresponding CPEntry reference count.
704 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
705 assert(CPE && "Cannot find a corresponding CPEntry!");
706 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000707
Evan Chenga8e29892007-01-19 07:51:42 +0000708 // Instructions can only use one CP entry, don't bother scanning the
709 // rest of the operands.
710 break;
711 }
712 }
Evan Chenga8e29892007-01-19 07:51:42 +0000713 }
714}
715
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000716/// ComputeBlockSize - Compute the size and some alignment information for MBB.
717/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000718void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000719 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
720 BBI.Size = 0;
721 BBI.Unalign = 0;
722 BBI.PostAlign = 0;
723
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000724 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
725 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000726 BBI.Size += TII->GetInstSizeInBytes(I);
727 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
728 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000729 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000730 BBI.Unalign = isThumb ? 1 : 2;
731 }
732
733 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000734 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000735 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000736 MBB->getParent()->EnsureAlignment(2);
737 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000738}
739
Evan Chenga8e29892007-01-19 07:51:42 +0000740/// GetOffsetOf - Return the current offset of the specified machine instruction
741/// from the start of the function. This offset changes as stuff is moved
742/// around inside the function.
743unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
744 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000745
Evan Chenga8e29892007-01-19 07:51:42 +0000746 // The offset is composed of two things: the sum of the sizes of all MBB's
747 // before this instruction's block, and the offset from the start of the block
748 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000749 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000750
751 // Sum instructions before MI in MBB.
752 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
753 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
754 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000755 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000756 }
757}
758
759/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
760/// ID.
761static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
762 const MachineBasicBlock *RHS) {
763 return LHS->getNumber() < RHS->getNumber();
764}
765
766/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
767/// machine function, it upsets all of the block numbers. Renumber the blocks
768/// and update the arrays that parallel this numbering.
769void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000770 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000771 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000772
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000773 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000774 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000775 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000776
777 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000778 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000779 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000780 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
781 CompareMBBNumbers);
782 WaterList.insert(IP, NewBB);
783}
784
785
786/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000787/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000788/// account for this change and returns the newly created block.
789MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000790 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000791 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000792
793 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000794 MachineBasicBlock *NewBB =
795 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000796 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000797 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000798
Evan Chenga8e29892007-01-19 07:51:42 +0000799 // Splice the instructions starting with MI over to NewBB.
800 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000801
Evan Chenga8e29892007-01-19 07:51:42 +0000802 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000803 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000804 // There doesn't seem to be meaningful DebugInfo available; this doesn't
805 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000806 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000807 if (!isThumb)
808 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
809 else
810 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
811 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000812 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000813
Evan Chenga8e29892007-01-19 07:51:42 +0000814 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000815 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000816
Evan Chenga8e29892007-01-19 07:51:42 +0000817 // OrigBB branches to NewBB.
818 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000819
Evan Chenga8e29892007-01-19 07:51:42 +0000820 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000821 // This is almost the same as UpdateForInsertedWaterBlock, except that
822 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000823 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000824
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000825 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000826 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000827 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000828
Bob Wilson84945262009-05-12 17:09:30 +0000829 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000830 // available water after it (but not if it's already there, which happens
831 // when splitting before a conditional branch that is followed by an
832 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000833 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
835 CompareMBBNumbers);
836 MachineBasicBlock* WaterBB = *IP;
837 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000838 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000839 else
840 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000841 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000842
Dale Johannesen8086d582010-07-23 22:50:23 +0000843 // Figure out how large the OrigBB is. As the first half of the original
844 // block, it cannot contain a tablejump. The size includes
845 // the new jump we added. (It should be possible to do this without
846 // recounting everything, but it's very confusing, and this is rarely
847 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000848 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000849
Dale Johannesen8086d582010-07-23 22:50:23 +0000850 // Figure out how large the NewMBB is. As the second half of the original
851 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000852 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000853
Dale Johannesen99c49a42007-02-25 00:47:03 +0000854 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000855 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000856
857 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000858}
859
Dale Johannesen8593e412007-04-29 19:19:30 +0000860/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000861/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000862/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000863bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000864 unsigned TrialOffset, unsigned MaxDisp,
865 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000866 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
867 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000868 // Effectively, the valid range of displacements is 2 bytes smaller for such
869 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000870 unsigned TotalAdj = 0;
871 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000872 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000873 TotalAdj = 2;
874 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000875 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000876 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000877 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000878 TotalAdj += 2;
879 }
880
881 // In Thumb2 mode, later branch adjustments can shift instructions up and
882 // cause alignment change. In the worst case scenario this can cause the
883 // user's effective address to be subtracted by 2 and the CPE's address to
884 // be plus 2.
885 if (isThumb2 && TotalAdj != 4)
886 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000887
Dale Johannesen99c49a42007-02-25 00:47:03 +0000888 if (UserOffset <= TrialOffset) {
889 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000890 if (TrialOffset - UserOffset <= MaxDisp)
891 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000892 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000893 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000894 if (UserOffset - TrialOffset <= MaxDisp)
895 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000896 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000897 }
898 return false;
899}
900
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901/// WaterIsInRange - Returns true if a CPE placed after the specified
902/// Water (a basic block) will be in range for the specific MI.
903
904bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000905 MachineBasicBlock* Water, CPUser &U) {
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000906 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907
Dale Johannesend959aa42007-04-02 20:31:06 +0000908 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000909 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000910 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000911 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000912
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000913 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000914}
915
916/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000917/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000918bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000919 MachineInstr *CPEMI, unsigned MaxDisp,
920 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000921 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000922 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000923
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000924 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000925 DEBUG({
926 unsigned Block = MI->getParent()->getNumber();
927 const BasicBlockInfo &BBI = BBInfo[Block];
928 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
929 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000930 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000931 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000932 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
933 << format("CPE address=%#x offset=%+d: ", CPEOffset,
934 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000935 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000936 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000937
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000938 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000939}
940
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000941#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000942/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
943/// unconditionally branches to its only successor.
944static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
945 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
946 return false;
947
948 MachineBasicBlock *Succ = *MBB->succ_begin();
949 MachineBasicBlock *Pred = *MBB->pred_begin();
950 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000951 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
952 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000953 return PredMI->getOperand(0).getMBB() == Succ;
954 return false;
955}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000956#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000957
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000958void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000959 MachineFunction *MF = BB->getParent();
960 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
961 // Get the offset and known bits at the end of the layout predecessor.
962 unsigned Offset = BBInfo[i - 1].postOffset();
963 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
964
965 // Add padding before an aligned block. This may teach us more bits.
966 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
967 Offset = WorstCaseAlign(Offset, Align, KnownBits);
968 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +0000969 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000970
971 // This is where block i begins.
972 BBInfo[i].Offset = Offset;
973 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +0000974 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000975}
976
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000977/// DecrementOldEntry - find the constant pool entry with index CPI
978/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000979/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000980/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000981
Evan Chenged884f32007-04-03 23:39:48 +0000982bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000983 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000984 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
985 assert(CPE && "Unexpected!");
986 if (--CPE->RefCount == 0) {
987 RemoveDeadCPEMI(CPEMI);
988 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000989 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000990 return true;
991 }
992 return false;
993}
994
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000995/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
996/// if not, see if an in-range clone of the CPE is in range, and if so,
997/// change the data structures so the user references the clone. Returns:
998/// 0 = no existing entry found
999/// 1 = entry found, and there were no code insertions or deletions
1000/// 2 = entry found, and there were code insertions or deletions
1001int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1002{
1003 MachineInstr *UserMI = U.MI;
1004 MachineInstr *CPEMI = U.CPEMI;
1005
1006 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001007 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001008 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001009 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001010 }
1011
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001012 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001013 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001014 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1015 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1016 // We already tried this one
1017 if (CPEs[i].CPEMI == CPEMI)
1018 continue;
1019 // Removing CPEs can leave empty entries, skip
1020 if (CPEs[i].CPEMI == NULL)
1021 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001022 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001023 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001024 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001025 // Point the CPUser node to the replacement
1026 U.CPEMI = CPEs[i].CPEMI;
1027 // Change the CPI in the instruction operand to refer to the clone.
1028 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001029 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001030 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001031 break;
1032 }
1033 // Adjust the refcount of the clone...
1034 CPEs[i].RefCount++;
1035 // ...and the original. If we didn't remove the old entry, none of the
1036 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001037 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001038 }
1039 }
1040 return 0;
1041}
1042
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001043/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1044/// the specific unconditional branch instruction.
1045static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001046 switch (Opc) {
1047 case ARM::tB:
1048 return ((1<<10)-1)*2;
1049 case ARM::t2B:
1050 return ((1<<23)-1)*2;
1051 default:
1052 break;
1053 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001054
David Goodwin5e47a9a2009-06-30 18:04:13 +00001055 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001056}
1057
Bob Wilsonb9239532009-10-15 20:49:47 +00001058/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001059/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001060/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001061/// is set to the WaterList entry. For Thumb, prefer water that will not
1062/// introduce padding to water that will. To ensure that this pass
1063/// terminates, the CPE location for a particular CPUser is only allowed to
1064/// move to a lower address, so search backward from the end of the list and
1065/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001066bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001067 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001068 if (WaterList.empty())
1069 return false;
1070
Bob Wilson32c50e82009-10-12 20:45:53 +00001071 bool FoundWaterThatWouldPad = false;
1072 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001073 for (water_iterator IP = prior(WaterList.end()),
1074 B = WaterList.begin();; --IP) {
1075 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001076 // Check if water is in range and is either at a lower address than the
1077 // current "high water mark" or a new water block that was created since
1078 // the previous iteration by inserting an unconditional branch. In the
1079 // latter case, we want to allow resetting the high water mark back to
1080 // this new water since we haven't seen it before. Inserting branches
1081 // should be relatively uncommon and when it does happen, we want to be
1082 // sure to take advantage of it for all the CPEs near that block, so that
1083 // we don't insert more branches than necessary.
1084 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1085 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1086 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001087 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001088 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001089 // This is valid Water, but would introduce padding. Remember
1090 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001091 if (!FoundWaterThatWouldPad) {
1092 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001093 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001094 }
Bob Wilson3b757352009-10-12 19:04:03 +00001095 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001096 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001097 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001098 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001099 }
Bob Wilson3b757352009-10-12 19:04:03 +00001100 if (IP == B)
1101 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001102 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001103 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001104 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001105 return true;
1106 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001107 return false;
1108}
1109
Bob Wilson84945262009-05-12 17:09:30 +00001110/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001111/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1112/// block is used if in range, and the conditional branch munged so control
1113/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001114/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001115/// block following which the new island can be inserted (the WaterList
1116/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001117void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001118 unsigned UserOffset,
1119 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001120 CPUser &U = CPUsers[CPUserIndex];
1121 MachineInstr *UserMI = U.MI;
1122 MachineInstr *CPEMI = U.CPEMI;
1123 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001124 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001125
Bob Wilson36fa5322009-10-15 05:10:36 +00001126 // If the block does not end in an unconditional branch already, and if the
1127 // end of the block is within range, make new water there. (The addition
1128 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1129 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001130 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001131 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001132 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001133 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001134 if (&UserMBB->back() == UserMI)
1135 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001136 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001137 // Add an unconditional branch from UserMBB to fallthrough block.
1138 // Record it for branch lengthening; this new branch will not get out of
1139 // range, but if the preceding conditional branch is out of range, the
1140 // targets will be exchanged, and the altered branch may be out of
1141 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001142 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001143 if (!isThumb)
1144 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1145 else
1146 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1147 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001148 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001149 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001150 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001151 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001152 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001153 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001154 } else {
1155 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001156 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001157 // and constant pool entries are 4 bytes: if instruction I references
1158 // island CPE, and instruction I+1 references CPE', it will
1159 // not work well to put CPE as far forward as possible, since then
1160 // CPE' cannot immediately follow it (that location is 2 bytes
1161 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001162 // a new island. So, we make a first guess, then walk through the
1163 // instructions between the one currently being looked at and the
1164 // possible insertion point, and make sure any other instructions
1165 // that reference CPEs will be able to use the same island area;
1166 // if not, we back up the insertion point.
1167
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001168 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001169 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001170 // island is handled inside OffsetIsInRange.
1171 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172 // This could point off the end of the block if we've already got
1173 // constant pool entries following this block; only the last one is
1174 // in the water list. Back past any possible branches (allow for a
1175 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001176 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1177 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001178 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001179 unsigned EndInsertOffset = BaseInsertOffset +
1180 CPEMI->getOperand(2).getImm();
1181 MachineBasicBlock::iterator MI = UserMI;
1182 ++MI;
1183 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001184 unsigned NumCPUsers = CPUsers.size();
1185 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001186 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001187 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001188 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001189 MI = llvm::next(MI)) {
1190 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001191 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001192 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001193 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1194 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001195 }
1196 // This is overly conservative, as we don't account for CPEMIs
1197 // being reused within the block, but it doesn't matter much.
1198 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1199 CPUIndex++;
1200 }
Evan Cheng719510a2010-08-12 20:30:05 +00001201
1202 // Remember the last IT instruction.
1203 if (MI->getOpcode() == ARM::t2IT)
1204 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001205 }
Evan Cheng719510a2010-08-12 20:30:05 +00001206
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001207 DEBUG(dbgs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001208 --MI;
1209
1210 // Avoid splitting an IT block.
1211 if (LastIT) {
1212 unsigned PredReg = 0;
1213 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1214 if (CC != ARMCC::AL)
1215 MI = LastIT;
1216 }
1217 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001218 }
1219}
1220
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001221/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001222/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223/// place in-range. Return true if we changed any addresses (thus must run
1224/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001225bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001226 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001227 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001228 MachineInstr *UserMI = U.MI;
1229 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001230 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001231 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001232 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001233 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001234 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001235
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001236 // See if the current entry is within range, or there is a clone of it
1237 // in range.
1238 int result = LookForExistingCPEntry(U, UserOffset);
1239 if (result==1) return false;
1240 else if (result==2) return true;
1241
1242 // No existing clone of this CPE is within range.
1243 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001244 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001245
Bob Wilsonf98032e2009-10-12 21:23:15 +00001246 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001247 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1248 MachineBasicBlock *NewMBB;
1249 water_iterator IP;
1250 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001251 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001252 MachineBasicBlock *WaterBB = *IP;
1253
1254 // If the original WaterList entry was "new water" on this iteration,
1255 // propagate that to the new island. This is just keeping NewWaterList
1256 // updated to match the WaterList, which will be updated below.
1257 if (NewWaterList.count(WaterBB)) {
1258 NewWaterList.erase(WaterBB);
1259 NewWaterList.insert(NewIsland);
1260 }
1261 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001262 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001263
1264 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001265 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001266 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001267 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001268
1269 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1270 // called while handling branches so that the water will be seen on the
1271 // next iteration for constant pools, but in this context, we don't want
1272 // it. Check for this so it will be removed from the WaterList.
1273 // Also remove any entry from NewWaterList.
1274 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1275 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1276 if (IP != WaterList.end())
1277 NewWaterList.erase(WaterBB);
1278
1279 // We are adding new water. Update NewWaterList.
1280 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001281 }
1282
Bob Wilsonb9239532009-10-15 20:49:47 +00001283 // Remove the original WaterList entry; we want subsequent insertions in
1284 // this vicinity to go after the one we're about to insert. This
1285 // considerably reduces the number of times we have to move the same CPE
1286 // more than once and is also important to ensure the algorithm terminates.
1287 if (IP != WaterList.end())
1288 WaterList.erase(IP);
1289
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001290 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001291 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001292
1293 // Update internal data structures to account for the newly inserted MBB.
1294 UpdateForInsertedWaterBlock(NewIsland);
1295
1296 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001297 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001298
1299 // Now that we have an island to add the CPE to, clone the original CPE and
1300 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001301 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001302 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001303 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001304 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001305 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001306
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001307 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1308 NewIsland->setAlignment(2);
1309
Evan Chenga8e29892007-01-19 07:51:42 +00001310 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001311 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001312 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001313
Evan Chenga8e29892007-01-19 07:51:42 +00001314 // Finally, change the CPI in the instruction operand to be ID.
1315 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001316 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001317 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001318 break;
1319 }
Bob Wilson84945262009-05-12 17:09:30 +00001320
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001321 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001322 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001323
Evan Chenga8e29892007-01-19 07:51:42 +00001324 return true;
1325}
1326
Evan Chenged884f32007-04-03 23:39:48 +00001327/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1328/// sizes and offsets of impacted basic blocks.
1329void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1330 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001331 unsigned Size = CPEMI->getOperand(2).getImm();
1332 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001333 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001334 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001335 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001336 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001337 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001338 // empty, so fix this.
1339 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001340 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1341 Size += BBInfo[CPEBB->getNumber()].Size;
1342 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001343 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001344
1345 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1346 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001347 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001348 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001349 // An island has only one predecessor BB and one successor BB. Check if
1350 // this BB's predecessor jumps directly to this BB's successor. This
1351 // shouldn't happen currently.
1352 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1353 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001354}
1355
1356/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1357/// are zero.
1358bool ARMConstantIslands::RemoveUnusedCPEntries() {
1359 unsigned MadeChange = false;
1360 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1361 std::vector<CPEntry> &CPEs = CPEntries[i];
1362 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1363 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1364 RemoveDeadCPEMI(CPEs[j].CPEMI);
1365 CPEs[j].CPEMI = NULL;
1366 MadeChange = true;
1367 }
1368 }
Bob Wilson84945262009-05-12 17:09:30 +00001369 }
Evan Chenged884f32007-04-03 23:39:48 +00001370 return MadeChange;
1371}
1372
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001374/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001375bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1376 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001377 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001378 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001379 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001380
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001381 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001382 << " from BB#" << MI->getParent()->getNumber()
1383 << " max delta=" << MaxDisp
1384 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1385 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001386
Dale Johannesen8593e412007-04-29 19:19:30 +00001387 if (BrOffset <= DestOffset) {
1388 // Branch before the Dest.
1389 if (DestOffset-BrOffset <= MaxDisp)
1390 return true;
1391 } else {
1392 if (BrOffset-DestOffset <= MaxDisp)
1393 return true;
1394 }
1395 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001396}
1397
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001398/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1399/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001400bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001401 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001402 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001403
Evan Chengc0dbec72007-01-31 19:57:44 +00001404 // Check to see if the DestBB is already in-range.
1405 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001406 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001407
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001408 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001409 return FixUpUnconditionalBr(MF, Br);
1410 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001411}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001412
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001413/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1414/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001415/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001416/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001417bool
Evan Cheng5657c012009-07-29 02:18:14 +00001418ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001419 MachineInstr *MI = Br.MI;
1420 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001421 if (!isThumb1)
1422 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001423
1424 // Use BL to implement far jump.
1425 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001426 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001427 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001428 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001429 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001430 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001431
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001432 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001433
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001434 return true;
1435}
1436
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001437/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001438/// far away to fit in its displacement field. It is converted to an inverse
1439/// conditional branch + an unconditional branch to the destination.
1440bool
Evan Cheng5657c012009-07-29 02:18:14 +00001441ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001442 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001443 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001444
Bob Wilson39bf0512009-05-12 17:35:29 +00001445 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001446 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001447 // blt L1
1448 // =>
1449 // bge L2
1450 // b L1
1451 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001452 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001453 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001454 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001455
1456 // If the branch is at the end of its MBB and that has a fall-through block,
1457 // direct the updated conditional branch to the fall-through block. Otherwise,
1458 // split the MBB before the next instruction.
1459 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001460 MachineInstr *BMI = &MBB->back();
1461 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001462
Dan Gohmanfe601042010-06-22 15:08:57 +00001463 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001464 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001465 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001466 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001467 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001468 // condition and swap destinations:
1469 // beq L1
1470 // b L2
1471 // =>
1472 // bne L2
1473 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001474 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001475 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001476 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001477 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001478 BMI->getOperand(0).setMBB(DestBB);
1479 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001480 MI->getOperand(1).setImm(CC);
1481 return true;
1482 }
1483 }
1484 }
1485
1486 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001487 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001488 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001489 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001490 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001491 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001492 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001493 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001494 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001495 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001496
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001497 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001498 << " also invert condition and change dest. to BB#"
1499 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001500
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001501 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001502 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001503 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001504 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001505 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001506 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001507 if (isThumb)
1508 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1509 .addImm(ARMCC::AL).addReg(0);
1510 else
1511 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001512 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001513 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001514 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001515
1516 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001517 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001518 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001519 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001520 return true;
1521}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001522
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001523/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001524/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1525/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001526bool ARMConstantIslands::UndoLRSpillRestore() {
1527 bool MadeChange = false;
1528 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1529 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001530 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001531 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001532 MI->getOperand(2).getReg() == ARM::PC &&
1533 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001534 // Create the new insn and copy the predicate from the old.
1535 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1536 .addOperand(MI->getOperand(0))
1537 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001538 MI->eraseFromParent();
1539 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001540 }
1541 }
1542 return MadeChange;
1543}
Evan Cheng5657c012009-07-29 02:18:14 +00001544
Evan Chenga1efbbd2009-08-14 00:32:16 +00001545bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1546 bool MadeChange = false;
1547
1548 // Shrink ADR and LDR from constantpool.
1549 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1550 CPUser &U = CPUsers[i];
1551 unsigned Opcode = U.MI->getOpcode();
1552 unsigned NewOpc = 0;
1553 unsigned Scale = 1;
1554 unsigned Bits = 0;
1555 switch (Opcode) {
1556 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001557 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001558 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1559 NewOpc = ARM::tLEApcrel;
1560 Bits = 8;
1561 Scale = 4;
1562 }
1563 break;
1564 case ARM::t2LDRpci:
1565 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1566 NewOpc = ARM::tLDRpci;
1567 Bits = 8;
1568 Scale = 4;
1569 }
1570 break;
1571 }
1572
1573 if (!NewOpc)
1574 continue;
1575
1576 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1577 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1578 // FIXME: Check if offset is multiple of scale if scale is not 4.
1579 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1580 U.MI->setDesc(TII->get(NewOpc));
1581 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001582 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001583 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001584 ++NumT2CPShrunk;
1585 MadeChange = true;
1586 }
1587 }
1588
Evan Chenga1efbbd2009-08-14 00:32:16 +00001589 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001590 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001591 return MadeChange;
1592}
1593
1594bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001595 bool MadeChange = false;
1596
1597 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1598 ImmBranch &Br = ImmBranches[i];
1599 unsigned Opcode = Br.MI->getOpcode();
1600 unsigned NewOpc = 0;
1601 unsigned Scale = 1;
1602 unsigned Bits = 0;
1603 switch (Opcode) {
1604 default: break;
1605 case ARM::t2B:
1606 NewOpc = ARM::tB;
1607 Bits = 11;
1608 Scale = 2;
1609 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001610 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001611 NewOpc = ARM::tBcc;
1612 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001613 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001614 break;
1615 }
Evan Chengde17fb62009-10-31 23:46:45 +00001616 }
1617 if (NewOpc) {
1618 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1619 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1620 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1621 Br.MI->setDesc(TII->get(NewOpc));
1622 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001623 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001624 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001625 ++NumT2BrShrunk;
1626 MadeChange = true;
1627 }
1628 }
1629
1630 Opcode = Br.MI->getOpcode();
1631 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001632 continue;
1633
Evan Chengde17fb62009-10-31 23:46:45 +00001634 NewOpc = 0;
1635 unsigned PredReg = 0;
1636 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1637 if (Pred == ARMCC::EQ)
1638 NewOpc = ARM::tCBZ;
1639 else if (Pred == ARMCC::NE)
1640 NewOpc = ARM::tCBNZ;
1641 if (!NewOpc)
1642 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001643 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001644 // Check if the distance is within 126. Subtract starting offset by 2
1645 // because the cmp will be eliminated.
1646 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001647 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001648 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001649 MachineBasicBlock::iterator CmpMI = Br.MI;
1650 if (CmpMI != Br.MI->getParent()->begin()) {
1651 --CmpMI;
1652 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1653 unsigned Reg = CmpMI->getOperand(0).getReg();
1654 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1655 if (Pred == ARMCC::AL &&
1656 CmpMI->getOperand(1).getImm() == 0 &&
1657 isARMLowRegister(Reg)) {
1658 MachineBasicBlock *MBB = Br.MI->getParent();
1659 MachineInstr *NewBR =
1660 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1661 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1662 CmpMI->eraseFromParent();
1663 Br.MI->eraseFromParent();
1664 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001665 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001666 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001667 ++NumCBZ;
1668 MadeChange = true;
1669 }
Evan Chengde17fb62009-10-31 23:46:45 +00001670 }
1671 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001672 }
1673 }
1674
1675 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001676}
1677
Evan Chenga1efbbd2009-08-14 00:32:16 +00001678/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1679/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001680bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1681 bool MadeChange = false;
1682
1683 // FIXME: After the tables are shrunk, can we get rid some of the
1684 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001685 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001686 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001687
Evan Cheng5657c012009-07-29 02:18:14 +00001688 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1689 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1690 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001691 const MCInstrDesc &MCID = MI->getDesc();
1692 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001693 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001694 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1695 unsigned JTI = JTOP.getIndex();
1696 assert(JTI < JT.size());
1697
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001698 bool ByteOk = true;
1699 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001700 unsigned JTOffset = GetOffsetOf(MI) + 4;
1701 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001702 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1703 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001704 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001705 // Negative offset is not ok. FIXME: We should change BB layout to make
1706 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001707 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001708 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001709 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001710 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001711 HalfWordOk = false;
1712 if (!ByteOk && !HalfWordOk)
1713 break;
1714 }
1715
1716 if (ByteOk || HalfWordOk) {
1717 MachineBasicBlock *MBB = MI->getParent();
1718 unsigned BaseReg = MI->getOperand(0).getReg();
1719 bool BaseRegKill = MI->getOperand(0).isKill();
1720 if (!BaseRegKill)
1721 continue;
1722 unsigned IdxReg = MI->getOperand(1).getReg();
1723 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001724
1725 // Scan backwards to find the instruction that defines the base
1726 // register. Due to post-RA scheduling, we can't count on it
1727 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001728 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001729 MachineBasicBlock::iterator B = MBB->begin();
1730 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1731 --PrevI;
1732
1733 // If for some reason we didn't find it, we can't do anything, so
1734 // just skip this one.
1735 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001736 continue;
1737
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001738 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001739 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001740 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001741 // Make sure it only defines the base register and kills any uses
1742 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001743 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1744 const MachineOperand &MO = AddrMI->getOperand(k);
1745 if (!MO.isReg() || !MO.getReg())
1746 continue;
1747 if (MO.isDef() && MO.getReg() != BaseReg) {
1748 OptOk = false;
1749 break;
1750 }
1751 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1752 OptOk = false;
1753 break;
1754 }
1755 }
1756 if (!OptOk)
1757 continue;
1758
Owen Anderson6b8719f2010-12-13 22:51:08 +00001759 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001760 // that gave us the initial base register definition.
1761 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1762 ;
1763
Owen Anderson6b8719f2010-12-13 22:51:08 +00001764 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001765 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001766 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001767 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001768 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001769 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001770 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001771
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001772 if (!OptOk)
1773 continue;
1774
Jim Grosbachd092a872010-11-29 21:28:32 +00001775 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001776 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1777 .addReg(IdxReg, getKillRegState(IdxRegKill))
1778 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1779 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1780 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1781 // is 2-byte aligned. For now, asm printer will fix it up.
1782 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1783 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1784 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1785 OrigSize += TII->GetInstSizeInBytes(MI);
1786
1787 AddrMI->eraseFromParent();
1788 LeaMI->eraseFromParent();
1789 MI->eraseFromParent();
1790
1791 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001792 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001793 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001794
1795 ++NumTBs;
1796 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001797 }
1798 }
1799
1800 return MadeChange;
1801}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001802
Jim Grosbach9249efe2009-11-16 18:55:47 +00001803/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1804/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001805bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1806 bool MadeChange = false;
1807
1808 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001809 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001810
Jim Grosbach80697d12009-11-12 17:25:07 +00001811 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1812 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1813 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001814 const MCInstrDesc &MCID = MI->getDesc();
1815 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001816 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001817 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1818 unsigned JTI = JTOP.getIndex();
1819 assert(JTI < JT.size());
1820
1821 // We prefer if target blocks for the jump table come after the jump
1822 // instruction so we can use TB[BH]. Loop through the target blocks
1823 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001824 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001825 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1826 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1827 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001828 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001829
Jim Grosbach08cbda52009-11-16 18:58:52 +00001830 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001831 // The destination precedes the switch. Try to move the block forward
1832 // so we have a positive offset.
1833 MachineBasicBlock *NewBB =
1834 AdjustJTTargetBlockForward(MBB, MI->getParent());
1835 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001836 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001837 MadeChange = true;
1838 }
1839 }
1840 }
1841
1842 return MadeChange;
1843}
1844
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001845MachineBasicBlock *ARMConstantIslands::
1846AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1847{
1848 MachineFunction &MF = *BB->getParent();
1849
Jim Grosbach03e2d442010-07-07 22:53:35 +00001850 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001851 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001852 // table that branches back to the actual target. This is a very simple
1853 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001854 MachineBasicBlock *TBB = 0, *FBB = 0;
1855 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001856 SmallVector<MachineOperand, 4> CondPrior;
1857 MachineFunction::iterator BBi = BB;
1858 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001859
Jim Grosbachca215e72009-11-16 17:10:56 +00001860 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001861 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001862
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001863 // If the block ends in an unconditional branch, move it. The prior block
1864 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001865 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001866 if (!B && Cond.empty() && BB != MF.begin() &&
1867 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001868 BB->moveAfter(JTBB);
1869 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001870 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001871 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001872 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001873 ++NumJTMoved;
1874 return NULL;
1875 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001876
1877 // Create a new MBB for the code after the jump BB.
1878 MachineBasicBlock *NewBB =
1879 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1880 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1881 MF.insert(MBBI, NewBB);
1882
1883 // Add an unconditional branch from NewBB to BB.
1884 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1885 // correspond directly to anything in the source.
1886 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001887 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1888 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001889
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001890 // Update internal data structures to account for the newly inserted MBB.
1891 MF.RenumberBlocks(NewBB);
1892
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001893 // Update the CFG.
1894 NewBB->addSuccessor(BB);
1895 JTBB->removeSuccessor(BB);
1896 JTBB->addSuccessor(NewBB);
1897
Jim Grosbach80697d12009-11-12 17:25:07 +00001898 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001899 return NewBB;
1900}