blob: 19c311c4f280cd5c9fc93bcf2a3a485d101568c0 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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"
18#include "ARMMachineFunctionInfo.h"
19#include "ARMInstrInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
30using namespace llvm;
31
32STATISTIC(NumCPEs, "Number of constpool entries");
33STATISTIC(NumSplit, "Number of uncond branches inserted");
34STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
36
37namespace {
38 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
41 /// constant pool; instead, it places constants wherever it feels like with
42 /// special instructions.
43 ///
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51 /// by MBB Number. The two-byte pads required for Thumb alignment are
52 /// counted as part of the following block (i.e., the offset and size for
53 /// a padded block will both be ==2 mod 4).
54 std::vector<unsigned> BBSizes;
Bob Wilsonec92b492009-05-12 17:09:30 +000055
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
57 /// The two-byte pads required for Thumb alignment are counted as part of
58 /// the following block.
59 std::vector<unsigned> BBOffsets;
60
61 /// WaterList - A sorted list of basic blocks where islands could be placed
62 /// (i.e. blocks that don't fall through to the following block, due
63 /// to a return, unreachable, or unconditional branch).
64 std::vector<MachineBasicBlock*> WaterList;
65
66 /// CPUser - One user of a constant pool, keeping the machine instruction
67 /// pointer, the constant pool being referenced, and the max displacement
68 /// allowed from the instruction to the CP.
69 struct CPUser {
70 MachineInstr *MI;
71 MachineInstr *CPEMI;
72 unsigned MaxDisp;
73 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
75 };
Bob Wilsonec92b492009-05-12 17:09:30 +000076
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
79 std::vector<CPUser> CPUsers;
Bob Wilsonec92b492009-05-12 17:09:30 +000080
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 /// CPEntry - One per constant pool entry, keeping the machine instruction
82 /// pointer, the constpool index, and the number of CPUser's which
83 /// reference this entry.
84 struct CPEntry {
85 MachineInstr *CPEMI;
86 unsigned CPI;
87 unsigned RefCount;
88 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
90 };
91
92 /// CPEntries - Keep track of all of the constant pool entry machine
93 /// instructions. For each original constpool index (i.e. those that
94 /// existed upon entry to this pass), it keeps a vector of entries.
95 /// Original elements are cloned as we go along; the clones are
96 /// put in the vector of the original element, but have distinct CPIs.
97 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilsonec92b492009-05-12 17:09:30 +000098
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 /// ImmBranch - One per immediate branch, keeping the machine instruction
100 /// pointer, conditional or unconditional, the max displacement,
101 /// and (if isCond is true) the corresponding unconditional branch
102 /// opcode.
103 struct ImmBranch {
104 MachineInstr *MI;
105 unsigned MaxDisp : 31;
106 bool isCond : 1;
107 int UncondBr;
108 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
110 };
111
112 /// ImmBranches - Keep track of all the immediate branch instructions.
113 ///
114 std::vector<ImmBranch> ImmBranches;
115
116 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
117 ///
118 SmallVector<MachineInstr*, 4> PushPopMIs;
119
120 /// HasFarJump - True if any far jump instruction has been emitted during
121 /// the branch fix up pass.
122 bool HasFarJump;
123
124 const TargetInstrInfo *TII;
125 ARMFunctionInfo *AFI;
126 bool isThumb;
David Goodwinf6154702009-06-30 18:04:13 +0000127 bool isThumb2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 public:
129 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000130 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131
132 virtual bool runOnMachineFunction(MachineFunction &Fn);
133
134 virtual const char *getPassName() const {
135 return "ARM constant island placement and branch shortening pass";
136 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000137
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 private:
139 void DoInitialPlacement(MachineFunction &Fn,
140 std::vector<MachineInstr*> &CPEMIs);
141 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
142 void InitialFunctionScan(MachineFunction &Fn,
143 const std::vector<MachineInstr*> &CPEMIs);
144 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
145 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
146 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
147 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
148 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonec92b492009-05-12 17:09:30 +0000149 bool LookForWater(CPUser&U, unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 MachineBasicBlock** NewMBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000151 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 std::vector<MachineBasicBlock*>::iterator IP);
153 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
154 MachineBasicBlock** NewMBB);
155 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
156 void RemoveDeadCPEMI(MachineInstr *CPEMI);
157 bool RemoveUnusedCPEntries();
Bob Wilsonec92b492009-05-12 17:09:30 +0000158 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 MachineInstr *CPEMI, unsigned Disp,
160 bool DoDump);
161 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
162 CPUser &U);
163 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
164 unsigned Disp, bool NegativeOK);
165 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
166 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
167 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
168 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
169 bool UndoLRSpillRestore();
170
171 unsigned GetOffsetOf(MachineInstr *MI) const;
172 void dumpBBs();
173 void verify(MachineFunction &Fn);
174 };
175 char ARMConstantIslands::ID = 0;
176}
177
178/// verify - check BBOffsets, BBSizes, alignment of islands
179void ARMConstantIslands::verify(MachineFunction &Fn) {
180 assert(BBOffsets.size() == BBSizes.size());
181 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
182 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
183 if (isThumb) {
184 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
185 MBBI != E; ++MBBI) {
186 MachineBasicBlock *MBB = MBBI;
187 if (!MBB->empty() &&
188 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
189 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
190 BBSizes[MBB->getNumber()]%4 == 0) ||
191 (BBOffsets[MBB->getNumber()]%4 != 0 &&
192 BBSizes[MBB->getNumber()]%4 != 0));
193 }
194 }
195}
196
197/// print block size and offset information - debugging
198void ARMConstantIslands::dumpBBs() {
199 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000200 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 " size " << BBSizes[J] << "\n";
202 }
203}
204
205/// createARMConstantIslandPass - returns an instance of the constpool
206/// island pass.
207FunctionPass *llvm::createARMConstantIslandPass() {
208 return new ARMConstantIslands();
209}
210
211bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
212 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilsonec92b492009-05-12 17:09:30 +0000213
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 TII = Fn.getTarget().getInstrInfo();
215 AFI = Fn.getInfo<ARMFunctionInfo>();
216 isThumb = AFI->isThumbFunction();
David Goodwinf6154702009-06-30 18:04:13 +0000217 isThumb2 = AFI->isThumb2Function();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218
219 HasFarJump = false;
220
221 // Renumber all of the machine basic blocks in the function, guaranteeing that
222 // the numbers agree with the position of the block in the function.
223 Fn.RenumberBlocks();
224
Bob Wilsonec92b492009-05-12 17:09:30 +0000225 /// Thumb functions containing constant pools get 2-byte alignment.
226 /// This is so we can keep exact track of where the alignment padding goes.
227 /// Set default.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 AFI->setAlign(isThumb ? 1U : 2U);
229
230 // Perform the initial placement of the constant pool entries. To start with,
231 // we put them all at the end of the function.
232 std::vector<MachineInstr*> CPEMIs;
233 if (!MCP.isEmpty()) {
234 DoInitialPlacement(Fn, CPEMIs);
235 if (isThumb)
236 AFI->setAlign(2U);
237 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000238
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 /// The next UID to take is the first unused one.
Evan Chengd3c573a2008-11-08 00:51:41 +0000240 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilsonec92b492009-05-12 17:09:30 +0000241
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 // Do the initial scan of the function, building up information about the
243 // sizes of each block, the location of all the water, and finding all of the
244 // constant pool users.
245 InitialFunctionScan(Fn, CPEMIs);
246 CPEMIs.clear();
Bob Wilsonec92b492009-05-12 17:09:30 +0000247
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 /// Remove dead constant pool entries.
249 RemoveUnusedCPEntries();
250
251 // Iteratively place constant pool entries and fix up branches until there
252 // is no change.
253 bool MadeChange = false;
254 while (true) {
255 bool Change = false;
256 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
257 Change |= HandleConstantPoolUser(Fn, i);
258 DEBUG(dumpBBs());
259 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
260 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
261 DEBUG(dumpBBs());
262 if (!Change)
263 break;
264 MadeChange = true;
265 }
266
267 // After a while, this might be made debug-only, but it is not expensive.
268 verify(Fn);
269
270 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
271 // Undo the spill / restore of LR if possible.
272 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
273 MadeChange |= UndoLRSpillRestore();
274
275 BBSizes.clear();
276 BBOffsets.clear();
277 WaterList.clear();
278 CPUsers.clear();
279 CPEntries.clear();
280 ImmBranches.clear();
281 PushPopMIs.clear();
282
283 return MadeChange;
284}
285
286/// DoInitialPlacement - Perform the initial placement of the constant pool
287/// entries. To start with, we put them all at the end of the function.
288void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilsonec92b492009-05-12 17:09:30 +0000289 std::vector<MachineInstr*> &CPEMIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 // Create the basic block to hold the CPE's.
Dan Gohman221a4372008-07-07 23:14:23 +0000291 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
292 Fn.push_back(BB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000293
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 // Add all of the constants from the constant pool to the end block, use an
295 // identity mapping of CPI's to CPE's.
296 const std::vector<MachineConstantPoolEntry> &CPs =
297 Fn.getConstantPool()->getConstants();
Bob Wilsonec92b492009-05-12 17:09:30 +0000298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 const TargetData &TD = *Fn.getTarget().getTargetData();
300 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000301 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
303 // we would have to pad them out or something so that instructions stay
304 // aligned.
305 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
306 MachineInstr *CPEMI =
Dale Johannesene8a10c42009-02-13 02:25:56 +0000307 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 .addImm(i).addConstantPoolIndex(i).addImm(Size);
309 CPEMIs.push_back(CPEMI);
310
311 // Add a new CPEntry, but no corresponding CPUser yet.
312 std::vector<CPEntry> CPEs;
313 CPEs.push_back(CPEntry(CPEMI, i));
314 CPEntries.push_back(CPEs);
315 NumCPEs++;
316 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
317 }
318}
319
320/// BBHasFallthrough - Return true if the specified basic block can fallthrough
321/// into the block immediately after it.
322static bool BBHasFallthrough(MachineBasicBlock *MBB) {
323 // Get the next machine basic block in the function.
324 MachineFunction::iterator MBBI = MBB;
325 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
326 return false;
Bob Wilsonec92b492009-05-12 17:09:30 +0000327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328 MachineBasicBlock *NextBB = next(MBBI);
329 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
330 E = MBB->succ_end(); I != E; ++I)
331 if (*I == NextBB)
332 return true;
Bob Wilsonec92b492009-05-12 17:09:30 +0000333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 return false;
335}
336
337/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
338/// look up the corresponding CPEntry.
339ARMConstantIslands::CPEntry
340*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
341 const MachineInstr *CPEMI) {
342 std::vector<CPEntry> &CPEs = CPEntries[CPI];
343 // Number of entries per constpool index should be small, just do a
344 // linear search.
345 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
346 if (CPEs[i].CPEMI == CPEMI)
347 return &CPEs[i];
348 }
349 return NULL;
350}
351
352/// InitialFunctionScan - Do the initial scan of the function, building up
353/// information about the sizes of each block, the location of all the water,
354/// and finding all of the constant pool users.
355void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
356 const std::vector<MachineInstr*> &CPEMIs) {
357 unsigned Offset = 0;
358 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
359 MBBI != E; ++MBBI) {
360 MachineBasicBlock &MBB = *MBBI;
Bob Wilsonec92b492009-05-12 17:09:30 +0000361
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362 // If this block doesn't fall through into the next MBB, then this is
363 // 'water' that a constant pool island could be placed.
364 if (!BBHasFallthrough(&MBB))
365 WaterList.push_back(&MBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000366
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 unsigned MBBSize = 0;
368 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
369 I != E; ++I) {
370 // Add instruction size to MBBSize.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000371 MBBSize += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372
373 int Opc = I->getOpcode();
Chris Lattner5b930372008-01-07 07:27:27 +0000374 if (I->getDesc().isBranch()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 bool isCond = false;
376 unsigned Bits = 0;
377 unsigned Scale = 1;
378 int UOpc = Opc;
379 switch (Opc) {
380 case ARM::tBR_JTr:
David Goodwinf6154702009-06-30 18:04:13 +0000381 case ARM::t2BR_JTr:
David Goodwin13d2f4e2009-06-30 19:50:22 +0000382 case ARM::t2BR_JTm:
383 case ARM::t2BR_JTadd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 // A Thumb table jump may involve padding; for the offsets to
385 // be right, functions containing these must be 4-byte aligned.
386 AFI->setAlign(2U);
387 if ((Offset+MBBSize)%4 != 0)
388 MBBSize += 2; // padding
389 continue; // Does not get an entry in ImmBranches
390 default:
391 continue; // Ignore other JT branches
392 case ARM::Bcc:
393 isCond = true;
394 UOpc = ARM::B;
395 // Fallthrough
396 case ARM::B:
397 Bits = 24;
398 Scale = 4;
399 break;
400 case ARM::tBcc:
401 isCond = true;
402 UOpc = ARM::tB;
403 Bits = 8;
404 Scale = 2;
405 break;
406 case ARM::tB:
407 Bits = 11;
408 Scale = 2;
409 break;
David Goodwinf6154702009-06-30 18:04:13 +0000410 case ARM::t2Bcc:
411 isCond = true;
412 UOpc = ARM::t2B;
413 Bits = 20;
414 Scale = 2;
415 break;
416 case ARM::t2B:
417 Bits = 24;
418 Scale = 2;
419 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 }
421
422 // Record this immediate branch.
423 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
424 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
425 }
426
427 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
428 PushPopMIs.push_back(I);
429
430 // Scan the instructions for constant pool operands.
431 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000432 if (I->getOperand(op).isCPI()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 // We found one. The addressing mode tells us the max displacement
434 // from the PC that this instruction permits.
Bob Wilsonec92b492009-05-12 17:09:30 +0000435
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 // Basic size info comes from the TSFlags field.
437 unsigned Bits = 0;
438 unsigned Scale = 1;
Chris Lattner5b930372008-01-07 07:27:27 +0000439 unsigned TSFlags = I->getDesc().TSFlags;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000441 default:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 // Constant pool entries can reach anything.
443 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
444 continue;
445 if (I->getOpcode() == ARM::tLEApcrel) {
446 Bits = 8; // Taking the address of a CP entry.
447 break;
448 }
449 assert(0 && "Unknown addressing mode for CP reference!");
450 case ARMII::AddrMode1: // AM1: 8 bits << 2
451 Bits = 8;
452 Scale = 4; // Taking the address of a CP entry.
453 break;
454 case ARMII::AddrMode2:
455 Bits = 12; // +-offset_12
456 break;
457 case ARMII::AddrMode3:
458 Bits = 8; // +-offset_8
459 break;
460 // addrmode4 has no immediate offset.
461 case ARMII::AddrMode5:
462 Bits = 8;
463 Scale = 4; // +-(offset_8*4)
464 break;
Evan Cheng532cdc52009-06-29 07:51:04 +0000465 case ARMII::AddrModeT1_1:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 Bits = 5; // +offset_5
467 break;
Evan Cheng532cdc52009-06-29 07:51:04 +0000468 case ARMII::AddrModeT1_2:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 Bits = 5;
470 Scale = 2; // +(offset_5*2)
471 break;
Evan Cheng532cdc52009-06-29 07:51:04 +0000472 case ARMII::AddrModeT1_4:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 Bits = 5;
474 Scale = 4; // +(offset_5*4)
475 break;
Evan Cheng532cdc52009-06-29 07:51:04 +0000476 case ARMII::AddrModeT1_s:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 Bits = 8;
478 Scale = 4; // +(offset_8*4)
479 break;
Evan Cheng532cdc52009-06-29 07:51:04 +0000480 case ARMII::AddrModeT2_pc:
481 Bits = 12; // +-offset_12
482 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 }
484
485 // Remember that this is a user of a CP entry.
Chris Lattner6017d482007-12-30 23:10:15 +0000486 unsigned CPI = I->getOperand(op).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilsonec92b492009-05-12 17:09:30 +0000488 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
490
491 // Increment corresponding CPEntry reference count.
492 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
493 assert(CPE && "Cannot find a corresponding CPEntry!");
494 CPE->RefCount++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000495
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 // Instructions can only use one CP entry, don't bother scanning the
497 // rest of the operands.
498 break;
499 }
500 }
501
502 // In thumb mode, if this block is a constpool island, we may need padding
503 // so it's aligned on 4 byte boundary.
504 if (isThumb &&
505 !MBB.empty() &&
506 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
507 (Offset%4) != 0)
508 MBBSize += 2;
509
510 BBSizes.push_back(MBBSize);
511 BBOffsets.push_back(Offset);
512 Offset += MBBSize;
513 }
514}
515
516/// GetOffsetOf - Return the current offset of the specified machine instruction
517/// from the start of the function. This offset changes as stuff is moved
518/// around inside the function.
519unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
520 MachineBasicBlock *MBB = MI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000521
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 // The offset is composed of two things: the sum of the sizes of all MBB's
523 // before this instruction's block, and the offset from the start of the block
524 // it is in.
525 unsigned Offset = BBOffsets[MBB->getNumber()];
526
527 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
528 // alignment padding, and compensate if so.
Bob Wilsonec92b492009-05-12 17:09:30 +0000529 if (isThumb &&
530 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 Offset%4 != 0)
532 Offset += 2;
533
534 // Sum instructions before MI in MBB.
535 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
536 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
537 if (&*I == MI) return Offset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000538 Offset += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 }
540}
541
542/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
543/// ID.
544static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
545 const MachineBasicBlock *RHS) {
546 return LHS->getNumber() < RHS->getNumber();
547}
548
549/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
550/// machine function, it upsets all of the block numbers. Renumber the blocks
551/// and update the arrays that parallel this numbering.
552void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
553 // Renumber the MBB's to keep them consequtive.
554 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000555
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 // Insert a size into BBSizes to align it properly with the (newly
557 // renumbered) block numbers.
558 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
559
560 // Likewise for BBOffsets.
561 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000562
563 // Next, update WaterList. Specifically, we need to add NewMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 // available water after it.
565 std::vector<MachineBasicBlock*>::iterator IP =
566 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
567 CompareMBBNumbers);
568 WaterList.insert(IP, NewBB);
569}
570
571
572/// Split the basic block containing MI into two blocks, which are joined by
573/// an unconditional branch. Update datastructures and renumber blocks to
574/// account for this change and returns the newly created block.
575MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
576 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman221a4372008-07-07 23:14:23 +0000577 MachineFunction &MF = *OrigBB->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578
579 // Create a new MBB for the code after the OrigBB.
Bob Wilsonec92b492009-05-12 17:09:30 +0000580 MachineBasicBlock *NewBB =
581 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman221a4372008-07-07 23:14:23 +0000583 MF.insert(MBBI, NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000584
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 // Splice the instructions starting with MI over to NewBB.
586 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilsonec92b492009-05-12 17:09:30 +0000587
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 // Add an unconditional branch from OrigBB to NewBB.
589 // Note the new unconditional branch is not being recorded.
Dale Johannesene8a10c42009-02-13 02:25:56 +0000590 // There doesn't seem to be meaningful DebugInfo available; this doesn't
591 // correspond to anything in the source.
592 BuildMI(OrigBB, DebugLoc::getUnknownLoc(),
David Goodwinf6154702009-06-30 18:04:13 +0000593 TII->get(isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B)).addMBB(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 NumSplit++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000595
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 // Update the CFG. All succs of OrigBB are now succs of NewBB.
597 while (!OrigBB->succ_empty()) {
598 MachineBasicBlock *Succ = *OrigBB->succ_begin();
599 OrigBB->removeSuccessor(Succ);
600 NewBB->addSuccessor(Succ);
Bob Wilsonec92b492009-05-12 17:09:30 +0000601
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 // This pass should be run after register allocation, so there should be no
603 // PHI nodes to update.
604 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
605 && "PHI nodes should be eliminated by now!");
606 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000607
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 // OrigBB branches to NewBB.
609 OrigBB->addSuccessor(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000610
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 // Update internal data structures to account for the newly inserted MBB.
612 // This is almost the same as UpdateForInsertedWaterBlock, except that
613 // the Water goes after OrigBB, not NewBB.
Dan Gohman221a4372008-07-07 23:14:23 +0000614 MF.RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000615
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 // Insert a size into BBSizes to align it properly with the (newly
617 // renumbered) block numbers.
618 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 // Likewise for BBOffsets.
621 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
622
Bob Wilsonec92b492009-05-12 17:09:30 +0000623 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 // available water after it (but not if it's already there, which happens
625 // when splitting before a conditional branch that is followed by an
626 // unconditional branch - in that case we want to insert NewBB).
627 std::vector<MachineBasicBlock*>::iterator IP =
628 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
629 CompareMBBNumbers);
630 MachineBasicBlock* WaterBB = *IP;
631 if (WaterBB == OrigBB)
632 WaterList.insert(next(IP), NewBB);
633 else
634 WaterList.insert(IP, OrigBB);
635
636 // Figure out how large the first NewMBB is. (It cannot
637 // contain a constpool_entry or tablejump.)
638 unsigned NewBBSize = 0;
639 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
640 I != E; ++I)
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000641 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilsonec92b492009-05-12 17:09:30 +0000642
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 unsigned OrigBBI = OrigBB->getNumber();
644 unsigned NewBBI = NewBB->getNumber();
645 // Set the size of NewBB in BBSizes.
646 BBSizes[NewBBI] = NewBBSize;
Bob Wilsonec92b492009-05-12 17:09:30 +0000647
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 // We removed instructions from UserMBB, subtract that off from its size.
649 // Add 2 or 4 to the block to count the unconditional branch we added to it.
650 unsigned delta = isThumb ? 2 : 4;
651 BBSizes[OrigBBI] -= NewBBSize - delta;
652
653 // ...and adjust BBOffsets for NewBB accordingly.
654 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
655
656 // All BBOffsets following these blocks must be modified.
657 AdjustBBOffsetsAfter(NewBB, delta);
658
659 return NewBB;
660}
661
662/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilsonec92b492009-05-12 17:09:30 +0000663/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664/// constant pool entry).
Bob Wilsonec92b492009-05-12 17:09:30 +0000665bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000667 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
668 // purposes of the displacement computation; compensate for that here.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 // Effectively, the valid range of displacements is 2 bytes smaller for such
670 // references.
671 if (isThumb && UserOffset%4 !=0)
672 UserOffset -= 2;
673 // CPEs will be rounded up to a multiple of 4.
674 if (isThumb && TrialOffset%4 != 0)
675 TrialOffset += 2;
676
677 if (UserOffset <= TrialOffset) {
678 // User before the Trial.
679 if (TrialOffset-UserOffset <= MaxDisp)
680 return true;
681 } else if (NegativeOK) {
682 if (UserOffset-TrialOffset <= MaxDisp)
683 return true;
684 }
685 return false;
686}
687
688/// WaterIsInRange - Returns true if a CPE placed after the specified
689/// Water (a basic block) will be in range for the specific MI.
690
691bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
692 MachineBasicBlock* Water, CPUser &U)
693{
694 unsigned MaxDisp = U.MaxDisp;
695 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilsonec92b492009-05-12 17:09:30 +0000696 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 BBSizes[Water->getNumber()];
698
699 // If the CPE is to be inserted before the instruction, that will raise
700 // the offset of the instruction. (Currently applies only to ARM, so
701 // no alignment compensation attempted here.)
702 if (CPEOffset < UserOffset)
703 UserOffset += U.CPEMI->getOperand(2).getImm();
704
705 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
706}
707
708/// CPEIsInRange - Returns true if the distance between specific MI and
709/// specific ConstPool entry instruction can fit in MI's displacement field.
710bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
711 MachineInstr *CPEMI,
712 unsigned MaxDisp, bool DoDump) {
713 unsigned CPEOffset = GetOffsetOf(CPEMI);
714 assert(CPEOffset%4 == 0 && "Misaligned CPE");
715
716 if (DoDump) {
717 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
718 << " max delta=" << MaxDisp
719 << " insn address=" << UserOffset
720 << " CPE address=" << CPEOffset
721 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
722 }
723
724 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
725}
726
Evan Cheng10361732009-01-28 00:53:34 +0000727#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
729/// unconditionally branches to its only successor.
730static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
731 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
732 return false;
733
734 MachineBasicBlock *Succ = *MBB->succ_begin();
735 MachineBasicBlock *Pred = *MBB->pred_begin();
736 MachineInstr *PredMI = &Pred->back();
David Goodwinf6154702009-06-30 18:04:13 +0000737 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
738 || PredMI->getOpcode() == ARM::t2B)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 return PredMI->getOperand(0).getMBB() == Succ;
740 return false;
741}
Evan Cheng10361732009-01-28 00:53:34 +0000742#endif // NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743
Bob Wilsonec92b492009-05-12 17:09:30 +0000744void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 int delta) {
746 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
747 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
748 BBOffsets[i] += delta;
749 // If some existing blocks have padding, adjust the padding as needed, a
750 // bit tricky. delta can be negative so don't use % on that.
751 if (isThumb) {
752 MachineBasicBlock *MBB = MBBI;
753 if (!MBB->empty()) {
754 // Constant pool entries require padding.
755 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
756 unsigned oldOffset = BBOffsets[i] - delta;
757 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
758 // add new padding
759 BBSizes[i] += 2;
760 delta += 2;
761 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
762 // remove existing padding
763 BBSizes[i] -=2;
764 delta -= 2;
765 }
766 }
767 // Thumb jump tables require padding. They should be at the end;
768 // following unconditional branches are removed by AnalyzeBranch.
769 MachineInstr *ThumbJTMI = NULL;
David Goodwinf6154702009-06-30 18:04:13 +0000770 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
David Goodwin13d2f4e2009-06-30 19:50:22 +0000771 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
772 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
773 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 ThumbJTMI = prior(MBB->end());
775 if (ThumbJTMI) {
776 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
777 unsigned oldMIOffset = newMIOffset - delta;
778 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
779 // remove existing padding
780 BBSizes[i] -= 2;
781 delta -= 2;
782 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
783 // add new padding
784 BBSizes[i] += 2;
785 delta += 2;
786 }
787 }
788 if (delta==0)
789 return;
790 }
791 MBBI = next(MBBI);
792 }
793 }
794}
795
796/// DecrementOldEntry - find the constant pool entry with index CPI
797/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilsonec92b492009-05-12 17:09:30 +0000798/// becomes 0 remove the entry and instruction. Returns true if we removed
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799/// the entry, false if we didn't.
800
801bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
802 // Find the old entry. Eliminate it if it is no longer used.
803 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
804 assert(CPE && "Unexpected!");
805 if (--CPE->RefCount == 0) {
806 RemoveDeadCPEMI(CPEMI);
807 CPE->CPEMI = NULL;
808 NumCPEs--;
809 return true;
810 }
811 return false;
812}
813
814/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
815/// if not, see if an in-range clone of the CPE is in range, and if so,
816/// change the data structures so the user references the clone. Returns:
817/// 0 = no existing entry found
818/// 1 = entry found, and there were no code insertions or deletions
819/// 2 = entry found, and there were code insertions or deletions
820int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
821{
822 MachineInstr *UserMI = U.MI;
823 MachineInstr *CPEMI = U.CPEMI;
824
825 // Check to see if the CPE is already in-range.
826 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
827 DOUT << "In range\n";
828 return 1;
829 }
830
831 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner6017d482007-12-30 23:10:15 +0000832 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 std::vector<CPEntry> &CPEs = CPEntries[CPI];
834 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
835 // We already tried this one
836 if (CPEs[i].CPEMI == CPEMI)
837 continue;
838 // Removing CPEs can leave empty entries, skip
839 if (CPEs[i].CPEMI == NULL)
840 continue;
841 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
842 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
843 // Point the CPUser node to the replacement
844 U.CPEMI = CPEs[i].CPEMI;
845 // Change the CPI in the instruction operand to refer to the clone.
846 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000847 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +0000848 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 break;
850 }
851 // Adjust the refcount of the clone...
852 CPEs[i].RefCount++;
853 // ...and the original. If we didn't remove the old entry, none of the
854 // addresses changed, so we don't need another pass.
855 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
856 }
857 }
858 return 0;
859}
860
861/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
862/// the specific unconditional branch instruction.
863static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwinf6154702009-06-30 18:04:13 +0000864 switch (Opc) {
865 case ARM::tB:
866 return ((1<<10)-1)*2;
867 case ARM::t2B:
868 return ((1<<23)-1)*2;
869 default:
870 break;
871 }
872
873 return ((1<<23)-1)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874}
875
876/// AcceptWater - Small amount of common code factored out of the following.
877
Bob Wilsonec92b492009-05-12 17:09:30 +0000878MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 std::vector<MachineBasicBlock*>::iterator IP) {
880 DOUT << "found water in range\n";
881 // Remove the original WaterList entry; we want subsequent
882 // insertions in this vicinity to go after the one we're
883 // about to insert. This considerably reduces the number
884 // of times we have to move the same CPE more than once.
885 WaterList.erase(IP);
886 // CPE goes before following block (NewMBB).
887 return next(MachineFunction::iterator(WaterBB));
888}
889
890/// LookForWater - look for an existing entry in the WaterList in which
891/// we can place the CPE referenced from U so it's within range of U's MI.
892/// Returns true if found, false if not. If it returns true, *NewMBB
893/// is set to the WaterList entry.
894/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
895/// water that will not introduce padding to water that will; within each
896/// group, prefer the water that's farthest away.
897
898bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
899 MachineBasicBlock** NewMBB) {
900 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
901 MachineBasicBlock* WaterBBThatWouldPad = NULL;
902 if (!WaterList.empty()) {
903 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
904 B = WaterList.begin();; --IP) {
905 MachineBasicBlock* WaterBB = *IP;
906 if (WaterIsInRange(UserOffset, WaterBB, U)) {
907 if (isThumb &&
Bob Wilsonec92b492009-05-12 17:09:30 +0000908 (BBOffsets[WaterBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 BBSizes[WaterBB->getNumber()])%4 != 0) {
910 // This is valid Water, but would introduce padding. Remember
911 // it in case we don't find any Water that doesn't do this.
912 if (!WaterBBThatWouldPad) {
913 WaterBBThatWouldPad = WaterBB;
914 IPThatWouldPad = IP;
915 }
916 } else {
917 *NewMBB = AcceptWater(WaterBB, IP);
918 return true;
919 }
920 }
921 if (IP == B)
922 break;
923 }
924 }
925 if (isThumb && WaterBBThatWouldPad) {
926 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
927 return true;
928 }
929 return false;
930}
931
Bob Wilsonec92b492009-05-12 17:09:30 +0000932/// CreateNewWater - No existing WaterList entry will work for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
934/// block is used if in range, and the conditional branch munged so control
935/// flow is correct. Otherwise the block is split to create a hole with an
936/// unconditional branch around it. In either case *NewMBB is set to a
937/// block following which the new island can be inserted (the WaterList
938/// is not adjusted).
939
Bob Wilsonec92b492009-05-12 17:09:30 +0000940void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 unsigned UserOffset, MachineBasicBlock** NewMBB) {
942 CPUser &U = CPUsers[CPUserIndex];
943 MachineInstr *UserMI = U.MI;
944 MachineInstr *CPEMI = U.CPEMI;
945 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000946 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 BBSizes[UserMBB->getNumber()];
948 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
949
950 // If the use is at the end of the block, or the end of the block
951 // is within range, make new water there. (The addition below is
952 // for the unconditional branch we will be adding: 4 bytes on ARM,
953 // 2 on Thumb. Possible Thumb alignment padding is allowed for
954 // inside OffsetIsInRange.
Bob Wilsonec92b492009-05-12 17:09:30 +0000955 // If the block ends in an unconditional branch already, it is water,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 // and is known to be out of range, so we'll always be adding a branch.)
957 if (&UserMBB->back() == UserMI ||
958 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
959 U.MaxDisp, !isThumb)) {
960 DOUT << "Split at end of block\n";
961 if (&UserMBB->back() == UserMI)
962 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
963 *NewMBB = next(MachineFunction::iterator(UserMBB));
964 // Add an unconditional branch from UserMBB to fallthrough block.
965 // Record it for branch lengthening; this new branch will not get out of
966 // range, but if the preceding conditional branch is out of range, the
967 // targets will be exchanged, and the altered branch may be out of
968 // range, so the machinery has to know about it.
David Goodwinf6154702009-06-30 18:04:13 +0000969 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesene8a10c42009-02-13 02:25:56 +0000970 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
971 TII->get(UncondBr)).addMBB(*NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilsonec92b492009-05-12 17:09:30 +0000973 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 MaxDisp, false, UncondBr));
975 int delta = isThumb ? 2 : 4;
976 BBSizes[UserMBB->getNumber()] += delta;
977 AdjustBBOffsetsAfter(UserMBB, delta);
978 } else {
979 // What a big block. Find a place within the block to split it.
980 // This is a little tricky on Thumb since instructions are 2 bytes
981 // and constant pool entries are 4 bytes: if instruction I references
982 // island CPE, and instruction I+1 references CPE', it will
983 // not work well to put CPE as far forward as possible, since then
984 // CPE' cannot immediately follow it (that location is 2 bytes
985 // farther away from I+1 than CPE was from I) and we'd need to create
986 // a new island. So, we make a first guess, then walk through the
987 // instructions between the one currently being looked at and the
988 // possible insertion point, and make sure any other instructions
989 // that reference CPEs will be able to use the same island area;
990 // if not, we back up the insertion point.
991
992 // The 4 in the following is for the unconditional branch we'll be
993 // inserting (allows for long branch on Thumb). Alignment of the
994 // island is handled inside OffsetIsInRange.
995 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
996 // This could point off the end of the block if we've already got
997 // constant pool entries following this block; only the last one is
998 // in the water list. Back past any possible branches (allow for a
999 // conditional and a maximally long unconditional).
1000 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilsonec92b492009-05-12 17:09:30 +00001001 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 (isThumb ? 6 : 8);
1003 unsigned EndInsertOffset = BaseInsertOffset +
1004 CPEMI->getOperand(2).getImm();
1005 MachineBasicBlock::iterator MI = UserMI;
1006 ++MI;
1007 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001008 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 Offset < BaseInsertOffset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001010 Offset += TII->GetInstSizeInBytes(MI),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 MI = next(MI)) {
1012 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilsonec92b492009-05-12 17:09:30 +00001013 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1015 BaseInsertOffset -= (isThumb ? 2 : 4);
1016 EndInsertOffset -= (isThumb ? 2 : 4);
1017 }
1018 // This is overly conservative, as we don't account for CPEMIs
1019 // being reused within the block, but it doesn't matter much.
1020 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1021 CPUIndex++;
1022 }
1023 }
1024 DOUT << "Split in middle of big block\n";
1025 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1026 }
1027}
1028
1029/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsond6985d52009-05-12 17:35:29 +00001030/// is out-of-range. If so, pick up the constant pool value and move it some
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031/// place in-range. Return true if we changed any addresses (thus must run
1032/// another pass of branch lengthening), false otherwise.
Bob Wilsonec92b492009-05-12 17:09:30 +00001033bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1034 unsigned CPUserIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 CPUser &U = CPUsers[CPUserIndex];
1036 MachineInstr *UserMI = U.MI;
1037 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001038 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 unsigned Size = CPEMI->getOperand(2).getImm();
1040 MachineBasicBlock *NewMBB;
1041 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilsond6985d52009-05-12 17:35:29 +00001042 // hardware keeps in the PC (2 insns ahead of the reference).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1044
1045 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1046 // second instruction.
1047 if (UserMI->getOpcode() == ARM::tLEApcrel)
1048 UserOffset += 2;
Bob Wilsonec92b492009-05-12 17:09:30 +00001049
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 // See if the current entry is within range, or there is a clone of it
1051 // in range.
1052 int result = LookForExistingCPEntry(U, UserOffset);
1053 if (result==1) return false;
1054 else if (result==2) return true;
1055
1056 // No existing clone of this CPE is within range.
1057 // We will be generating a new clone. Get a UID for it.
Bob Wilsond6985d52009-05-12 17:35:29 +00001058 unsigned ID = AFI->createConstPoolEntryUId();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
1060 // Look for water where we can place this CPE. We look for the farthest one
1061 // away that will work. Forward references only for now (although later
1062 // we might find some that are backwards).
1063
1064 if (!LookForWater(U, UserOffset, &NewMBB)) {
1065 // No water found.
1066 DOUT << "No water found\n";
1067 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1068 }
1069
1070 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman221a4372008-07-07 23:14:23 +00001071 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1072 Fn.insert(NewMBB, NewIsland);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073
1074 // Update internal data structures to account for the newly inserted MBB.
1075 UpdateForInsertedWaterBlock(NewIsland);
1076
1077 // Decrement the old entry, and remove it if refcount becomes 0.
1078 DecrementOldEntry(CPI, CPEMI);
1079
1080 // Now that we have an island to add the CPE to, clone the original CPE and
1081 // add it to the island.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001082 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1083 TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1085 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1086 NumCPEs++;
1087
1088 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1089 // Compensate for .align 2 in thumb mode.
Bob Wilsonec92b492009-05-12 17:09:30 +00001090 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 Size += 2;
1092 // Increase the size of the island block to account for the new entry.
1093 BBSizes[NewIsland->getNumber()] += Size;
1094 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilsonec92b492009-05-12 17:09:30 +00001095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 // Finally, change the CPI in the instruction operand to be ID.
1097 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001098 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +00001099 UserMI->getOperand(i).setIndex(ID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 break;
1101 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001102
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilsonec92b492009-05-12 17:09:30 +00001104
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 return true;
1106}
1107
1108/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1109/// sizes and offsets of impacted basic blocks.
1110void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1111 MachineBasicBlock *CPEBB = CPEMI->getParent();
1112 unsigned Size = CPEMI->getOperand(2).getImm();
1113 CPEMI->eraseFromParent();
1114 BBSizes[CPEBB->getNumber()] -= Size;
1115 // All succeeding offsets have the current size value added in, fix this.
1116 if (CPEBB->empty()) {
1117 // In thumb mode, the size of island may be padded by two to compensate for
1118 // the alignment requirement. Then it will now be 2 when the block is
1119 // empty, so fix this.
1120 // All succeeding offsets have the current size value added in, fix this.
1121 if (BBSizes[CPEBB->getNumber()] != 0) {
1122 Size += BBSizes[CPEBB->getNumber()];
1123 BBSizes[CPEBB->getNumber()] = 0;
1124 }
1125 }
1126 AdjustBBOffsetsAfter(CPEBB, -Size);
1127 // An island has only one predecessor BB and one successor BB. Check if
1128 // this BB's predecessor jumps directly to this BB's successor. This
1129 // shouldn't happen currently.
1130 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1131 // FIXME: remove the empty blocks after all the work is done?
1132}
1133
1134/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1135/// are zero.
1136bool ARMConstantIslands::RemoveUnusedCPEntries() {
1137 unsigned MadeChange = false;
1138 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1139 std::vector<CPEntry> &CPEs = CPEntries[i];
1140 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1141 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1142 RemoveDeadCPEMI(CPEs[j].CPEMI);
1143 CPEs[j].CPEMI = NULL;
1144 MadeChange = true;
1145 }
1146 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001147 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 return MadeChange;
1149}
1150
1151/// BBIsInRange - Returns true if the distance between specific MI and
1152/// specific BB can fit in MI's displacement field.
1153bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1154 unsigned MaxDisp) {
1155 unsigned PCAdj = isThumb ? 4 : 8;
1156 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1157 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1158
1159 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1160 << " from BB#" << MI->getParent()->getNumber()
1161 << " max delta=" << MaxDisp
1162 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1163 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1164
1165 if (BrOffset <= DestOffset) {
1166 // Branch before the Dest.
1167 if (DestOffset-BrOffset <= MaxDisp)
1168 return true;
1169 } else {
1170 if (BrOffset-DestOffset <= MaxDisp)
1171 return true;
1172 }
1173 return false;
1174}
1175
1176/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1177/// away to fit in its displacement field.
1178bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1179 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001180 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181
1182 // Check to see if the DestBB is already in-range.
1183 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1184 return false;
1185
1186 if (!Br.isCond)
1187 return FixUpUnconditionalBr(Fn, Br);
1188 return FixUpConditionalBr(Fn, Br);
1189}
1190
1191/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1192/// too far away to fit in its displacement field. If the LR register has been
1193/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsond6985d52009-05-12 17:35:29 +00001194/// Otherwise, add an intermediate branch instruction to a branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195bool
1196ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1197 MachineInstr *MI = Br.MI;
1198 MachineBasicBlock *MBB = MI->getParent();
David Goodwinf6154702009-06-30 18:04:13 +00001199 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200
1201 // Use BL to implement far jump.
1202 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner86bb02f2008-01-11 18:10:50 +00001203 MI->setDesc(TII->get(ARM::tBfar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 BBSizes[MBB->getNumber()] += 2;
1205 AdjustBBOffsetsAfter(MBB, 2);
1206 HasFarJump = true;
1207 NumUBrFixed++;
1208
1209 DOUT << " Changed B to long jump " << *MI;
1210
1211 return true;
1212}
1213
1214/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1215/// far away to fit in its displacement field. It is converted to an inverse
1216/// conditional branch + an unconditional branch to the destination.
1217bool
1218ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1219 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001220 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221
Bob Wilsond6985d52009-05-12 17:35:29 +00001222 // Add an unconditional branch to the destination and invert the branch
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 // condition to jump over it:
1224 // blt L1
1225 // =>
1226 // bge L2
1227 // b L1
1228 // L2:
Chris Lattnera96056a2007-12-30 20:49:49 +00001229 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 CC = ARMCC::getOppositeCondition(CC);
1231 unsigned CCReg = MI->getOperand(2).getReg();
1232
1233 // If the branch is at the end of its MBB and that has a fall-through block,
1234 // direct the updated conditional branch to the fall-through block. Otherwise,
1235 // split the MBB before the next instruction.
1236 MachineBasicBlock *MBB = MI->getParent();
1237 MachineInstr *BMI = &MBB->back();
1238 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1239
1240 NumCBrFixed++;
1241 if (BMI != MI) {
Dan Gohman221a4372008-07-07 23:14:23 +00001242 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsond6985d52009-05-12 17:35:29 +00001244 // Last MI in the BB is an unconditional branch. Can we simply invert the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 // condition and swap destinations:
1246 // beq L1
1247 // b L2
1248 // =>
1249 // bne L2
1250 // b L1
Chris Lattner6017d482007-12-30 23:10:15 +00001251 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1253 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001254 BMI->getOperand(0).setMBB(DestBB);
1255 MI->getOperand(0).setMBB(NewDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 MI->getOperand(1).setImm(CC);
1257 return true;
1258 }
1259 }
1260 }
1261
1262 if (NeedSplit) {
1263 SplitBlockBeforeInstr(MI);
Bob Wilsond6985d52009-05-12 17:35:29 +00001264 // No need for the branch to the next block. We're adding an unconditional
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 // branch to the destination.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001266 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 BBSizes[MBB->getNumber()] -= delta;
1268 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1269 AdjustBBOffsetsAfter(SplitBB, -delta);
1270 MBB->back().eraseFromParent();
1271 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1272 }
1273 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilsonec92b492009-05-12 17:09:30 +00001274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 DOUT << " Insert B to BB#" << DestBB->getNumber()
1276 << " also invert condition and change dest. to BB#"
1277 << NextBB->getNumber() << "\n";
1278
1279 // Insert a new conditional branch and a new unconditional branch.
1280 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001281 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1282 TII->get(MI->getOpcode()))
1283 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 Br.MI = &MBB->back();
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001285 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesene8a10c42009-02-13 02:25:56 +00001286 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001287 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1289 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1290
1291 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001292 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 MI->eraseFromParent();
1294
1295 // The net size change is an addition of one unconditional branch.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001296 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 AdjustBBOffsetsAfter(MBB, delta);
1298 return true;
1299}
1300
1301/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1302/// LR / restores LR to pc.
1303bool ARMConstantIslands::UndoLRSpillRestore() {
1304 bool MadeChange = false;
1305 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1306 MachineInstr *MI = PushPopMIs[i];
1307 if (MI->getOpcode() == ARM::tPOP_RET &&
1308 MI->getOperand(0).getReg() == ARM::PC &&
1309 MI->getNumExplicitOperands() == 1) {
Dale Johannesene8a10c42009-02-13 02:25:56 +00001310 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 MI->eraseFromParent();
1312 MadeChange = true;
1313 }
1314 }
1315 return MadeChange;
1316}