1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
18 #include "ARMAddressingModes.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMInstrInfo.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
38 STATISTIC(NumCPEs, "Number of constpool entries");
39 STATISTIC(NumSplit, "Number of uncond branches inserted");
40 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42 STATISTIC(NumTBs, "Number of table branches generated");
43 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
44 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
45 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
46 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
47 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
51 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
55 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
56 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
58 /// constant pool; instead, it places constants wherever it feels like with
59 /// special instructions.
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
66 class ARMConstantIslands : public MachineFunctionPass {
67 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
68 /// by MBB Number. The two-byte pads required for Thumb alignment are
69 /// counted as part of the following block (i.e., the offset and size for
70 /// a padded block will both be ==2 mod 4).
71 std::vector<unsigned> BBSizes;
73 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
74 /// The two-byte pads required for Thumb alignment are counted as part of
75 /// the following block.
76 std::vector<unsigned> BBOffsets;
78 /// WaterList - A sorted list of basic blocks where islands could be placed
79 /// (i.e. blocks that don't fall through to the following block, due
80 /// to a return, unreachable, or unconditional branch).
81 std::vector<MachineBasicBlock*> WaterList;
83 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
87 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
89 /// CPUser - One user of a constant pool, keeping the machine instruction
90 /// pointer, the constant pool being referenced, and the max displacement
91 /// allowed from the instruction to the CP. The HighWaterMark records the
92 /// highest basic block where a new CPEntry can be placed. To ensure this
93 /// pass terminates, the CP entries are initially placed at the end of the
94 /// function and then move monotonically to lower addresses. The
95 /// exception to this rule is when the current CP entry for a particular
96 /// CPUser is out of range, but there is another CP entry for the same
97 /// constant value in range. We want to use the existing in-range CP
98 /// entry, but if it later moves out of range, the search for new water
99 /// should resume where it left off. The HighWaterMark is used to record
104 MachineBasicBlock *HighWaterMark;
108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
111 HighWaterMark = CPEMI->getParent();
115 /// CPUsers - Keep track of all of the machine instructions that use various
116 /// constant pools and their max displacement.
117 std::vector<CPUser> CPUsers;
119 /// CPEntry - One per constant pool entry, keeping the machine instruction
120 /// pointer, the constpool index, and the number of CPUser's which
121 /// reference this entry.
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
130 /// CPEntries - Keep track of all of the constant pool entry machine
131 /// instructions. For each original constpool index (i.e. those that
132 /// existed upon entry to this pass), it keeps a vector of entries.
133 /// Original elements are cloned as we go along; the clones are
134 /// put in the vector of the original element, but have distinct CPIs.
135 std::vector<std::vector<CPEntry> > CPEntries;
137 /// ImmBranch - One per immediate branch, keeping the machine instruction
138 /// pointer, conditional or unconditional, the max displacement,
139 /// and (if isCond is true) the corresponding unconditional branch
143 unsigned MaxDisp : 31;
146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
150 /// ImmBranches - Keep track of all the immediate branch instructions.
152 std::vector<ImmBranch> ImmBranches;
154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
156 SmallVector<MachineInstr*, 4> PushPopMIs;
158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
165 /// HasInlineAsm - True if the function contains inline assembly.
168 const TargetInstrInfo *TII;
169 const ARMSubtarget *STI;
170 ARMFunctionInfo *AFI;
176 ARMConstantIslands() : MachineFunctionPass(&ID) {}
178 virtual bool runOnMachineFunction(MachineFunction &MF);
180 virtual const char *getPassName() const {
181 return "ARM constant island placement and branch shortening pass";
185 void DoInitialPlacement(MachineFunction &MF,
186 std::vector<MachineInstr*> &CPEMIs);
187 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
188 void JumpTableFunctionScan(MachineFunction &MF);
189 void InitialFunctionScan(MachineFunction &MF,
190 const std::vector<MachineInstr*> &CPEMIs);
191 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
192 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
193 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
194 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
195 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
196 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
197 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
198 MachineBasicBlock *&NewMBB);
199 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
200 void RemoveDeadCPEMI(MachineInstr *CPEMI);
201 bool RemoveUnusedCPEntries();
202 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
203 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
204 bool DoDump = false);
205 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
207 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
208 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
209 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
210 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
211 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
212 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
213 bool UndoLRSpillRestore();
214 bool OptimizeThumb2Instructions(MachineFunction &MF);
215 bool OptimizeThumb2Branches(MachineFunction &MF);
216 bool ReorderThumb2JumpTables(MachineFunction &MF);
217 bool OptimizeThumb2JumpTables(MachineFunction &MF);
218 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
219 MachineBasicBlock *JTBB);
221 unsigned GetOffsetOf(MachineInstr *MI) const;
223 void verify(MachineFunction &MF);
225 char ARMConstantIslands::ID = 0;
228 /// verify - check BBOffsets, BBSizes, alignment of islands
229 void ARMConstantIslands::verify(MachineFunction &MF) {
230 assert(BBOffsets.size() == BBSizes.size());
231 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
232 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
236 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
238 MachineBasicBlock *MBB = MBBI;
240 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
241 unsigned MBBId = MBB->getNumber();
242 assert(HasInlineAsm ||
243 (BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
244 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
248 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
249 CPUser &U = CPUsers[i];
250 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
251 assert (CPEIsInRange(U.MI, UserOffset, U.CPEMI, U.MaxDisp, U.NegOk, true));
255 /// print block size and offset information - debugging
256 void ARMConstantIslands::dumpBBs() {
257 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
258 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
259 << " size " << BBSizes[J] << "\n");
263 /// createARMConstantIslandPass - returns an instance of the constpool
265 FunctionPass *llvm::createARMConstantIslandPass() {
266 return new ARMConstantIslands();
269 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
270 MachineConstantPool &MCP = *MF.getConstantPool();
272 TII = MF.getTarget().getInstrInfo();
273 AFI = MF.getInfo<ARMFunctionInfo>();
274 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
276 isThumb = AFI->isThumbFunction();
277 isThumb1 = AFI->isThumb1OnlyFunction();
278 isThumb2 = AFI->isThumb2Function();
281 HasInlineAsm = false;
283 // Renumber all of the machine basic blocks in the function, guaranteeing that
284 // the numbers agree with the position of the block in the function.
287 // Try to reorder and otherwise adjust the block layout to make good use
288 // of the TB[BH] instructions.
289 bool MadeChange = false;
290 if (isThumb2 && AdjustJumpTableBlocks) {
291 JumpTableFunctionScan(MF);
292 MadeChange |= ReorderThumb2JumpTables(MF);
293 // Data is out of date, so clear it. It'll be re-computed later.
294 T2JumpTables.clear();
295 // Blocks may have shifted around. Keep the numbering up to date.
299 // Thumb1 functions containing constant pools get 4-byte alignment.
300 // This is so we can keep exact track of where the alignment padding goes.
302 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
304 AFI->setAlign(isThumb1 ? 1U : 2U);
306 // Perform the initial placement of the constant pool entries. To start with,
307 // we put them all at the end of the function.
308 std::vector<MachineInstr*> CPEMIs;
309 if (!MCP.isEmpty()) {
310 DoInitialPlacement(MF, CPEMIs);
315 /// The next UID to take is the first unused one.
316 AFI->initConstPoolEntryUId(CPEMIs.size());
318 // Do the initial scan of the function, building up information about the
319 // sizes of each block, the location of all the water, and finding all of the
320 // constant pool users.
321 InitialFunctionScan(MF, CPEMIs);
324 /// Remove dead constant pool entries.
325 RemoveUnusedCPEntries();
327 // Iteratively place constant pool entries and fix up branches until there
329 unsigned NoCPIters = 0, NoBRIters = 0;
331 bool CPChange = false;
332 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
333 CPChange |= HandleConstantPoolUser(MF, i);
334 if (CPChange && ++NoCPIters > 30)
335 llvm_unreachable("Constant Island pass failed to converge!");
338 // Clear NewWaterList now. If we split a block for branches, it should
339 // appear as "new water" for the next iteration of constant pool placement.
340 NewWaterList.clear();
342 bool BRChange = false;
343 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
344 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
345 if (BRChange && ++NoBRIters > 30)
346 llvm_unreachable("Branch Fix Up pass failed to converge!");
349 if (!CPChange && !BRChange)
354 // Shrink 32-bit Thumb2 branch, load, and store instructions.
356 MadeChange |= OptimizeThumb2Instructions(MF);
358 // After a while, this might be made debug-only, but it is not expensive.
361 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
362 // Undo the spill / restore of LR if possible.
363 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
364 MadeChange |= UndoLRSpillRestore();
373 T2JumpTables.clear();
378 /// DoInitialPlacement - Perform the initial placement of the constant pool
379 /// entries. To start with, we put them all at the end of the function.
380 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
381 std::vector<MachineInstr*> &CPEMIs) {
382 // Create the basic block to hold the CPE's.
383 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
386 // Add all of the constants from the constant pool to the end block, use an
387 // identity mapping of CPI's to CPE's.
388 const std::vector<MachineConstantPoolEntry> &CPs =
389 MF.getConstantPool()->getConstants();
391 const TargetData &TD = *MF.getTarget().getTargetData();
392 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
393 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
394 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
395 // we would have to pad them out or something so that instructions stay
397 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
398 MachineInstr *CPEMI =
399 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
400 .addImm(i).addConstantPoolIndex(i).addImm(Size);
401 CPEMIs.push_back(CPEMI);
403 // Add a new CPEntry, but no corresponding CPUser yet.
404 std::vector<CPEntry> CPEs;
405 CPEs.push_back(CPEntry(CPEMI, i));
406 CPEntries.push_back(CPEs);
408 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
413 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
414 /// into the block immediately after it.
415 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
416 // Get the next machine basic block in the function.
417 MachineFunction::iterator MBBI = MBB;
418 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
421 MachineBasicBlock *NextBB = next(MBBI);
422 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
423 E = MBB->succ_end(); I != E; ++I)
430 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
431 /// look up the corresponding CPEntry.
432 ARMConstantIslands::CPEntry
433 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
434 const MachineInstr *CPEMI) {
435 std::vector<CPEntry> &CPEs = CPEntries[CPI];
436 // Number of entries per constpool index should be small, just do a
438 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
439 if (CPEs[i].CPEMI == CPEMI)
445 /// JumpTableFunctionScan - Do a scan of the function, building up
446 /// information about the sizes of each block and the locations of all
448 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
449 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
451 MachineBasicBlock &MBB = *MBBI;
453 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
455 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
456 T2JumpTables.push_back(I);
460 /// InitialFunctionScan - Do the initial scan of the function, building up
461 /// information about the sizes of each block, the location of all the water,
462 /// and finding all of the constant pool users.
463 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
464 const std::vector<MachineInstr*> &CPEMIs) {
465 // First thing, see if the function has any inline assembly in it. If so,
466 // we have to be conservative about alignment assumptions, as we don't
467 // know for sure the size of any instructions in the inline assembly.
468 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
470 MachineBasicBlock &MBB = *MBBI;
471 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
473 if (I->getOpcode() == ARM::INLINEASM)
477 // Now go back through the instructions and build up our data structures
479 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
481 MachineBasicBlock &MBB = *MBBI;
483 // If this block doesn't fall through into the next MBB, then this is
484 // 'water' that a constant pool island could be placed.
485 if (!BBHasFallthrough(&MBB))
486 WaterList.push_back(&MBB);
488 unsigned MBBSize = 0;
489 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
491 // Add instruction size to MBBSize.
492 MBBSize += TII->GetInstSizeInBytes(I);
494 int Opc = I->getOpcode();
495 if (I->getDesc().isBranch()) {
502 continue; // Ignore other JT branches
504 // A Thumb1 table jump may involve padding; for the offsets to
505 // be right, functions containing these must be 4-byte aligned.
507 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
508 // FIXME: Add a pseudo ALIGN instruction instead.
509 MBBSize += 2; // padding
510 continue; // Does not get an entry in ImmBranches
512 T2JumpTables.push_back(I);
513 continue; // Does not get an entry in ImmBranches
544 // Record this immediate branch.
545 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
546 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
549 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
550 PushPopMIs.push_back(I);
552 if (Opc == ARM::CONSTPOOL_ENTRY)
555 // Scan the instructions for constant pool operands.
556 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
557 if (I->getOperand(op).isCPI()) {
558 // We found one. The addressing mode tells us the max displacement
559 // from the PC that this instruction permits.
561 // Basic size info comes from the TSFlags field.
565 bool IsSoImm = false;
569 llvm_unreachable("Unknown addressing mode for CP reference!");
572 // Taking the address of a CP entry.
574 // This takes a SoImm, which is 8 bit immediate rotated. We'll
575 // pretend the maximum offset is 255 * 4. Since each instruction
576 // 4 byte wide, this is always correct. We'll check for other
577 // displacements that fits in a SoImm as well.
583 case ARM::t2LEApcrel:
595 Bits = 12; // +-offset_12
602 Scale = 4; // +(offset_8*4)
608 Scale = 4; // +-(offset_8*4)
613 // Remember that this is a user of a CP entry.
614 unsigned CPI = I->getOperand(op).getIndex();
615 MachineInstr *CPEMI = CPEMIs[CPI];
616 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
617 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
619 // Increment corresponding CPEntry reference count.
620 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
621 assert(CPE && "Cannot find a corresponding CPEntry!");
624 // Instructions can only use one CP entry, don't bother scanning the
625 // rest of the operands.
630 // In thumb mode, if this block is a constpool island, we may need padding
631 // so it's aligned on 4 byte boundary.
634 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
635 ((Offset%4) != 0 || HasInlineAsm))
638 BBSizes.push_back(MBBSize);
639 BBOffsets.push_back(Offset);
644 /// GetOffsetOf - Return the current offset of the specified machine instruction
645 /// from the start of the function. This offset changes as stuff is moved
646 /// around inside the function.
647 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
648 MachineBasicBlock *MBB = MI->getParent();
650 // The offset is composed of two things: the sum of the sizes of all MBB's
651 // before this instruction's block, and the offset from the start of the block
653 unsigned Offset = BBOffsets[MBB->getNumber()];
655 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
656 // alignment padding, and compensate if so.
658 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
659 (Offset%4 != 0 || HasInlineAsm))
662 // Sum instructions before MI in MBB.
663 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
664 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
665 if (&*I == MI) return Offset;
666 Offset += TII->GetInstSizeInBytes(I);
670 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
672 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
673 const MachineBasicBlock *RHS) {
674 return LHS->getNumber() < RHS->getNumber();
677 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
678 /// machine function, it upsets all of the block numbers. Renumber the blocks
679 /// and update the arrays that parallel this numbering.
680 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
681 // Renumber the MBB's to keep them consequtive.
682 NewBB->getParent()->RenumberBlocks(NewBB);
684 // Insert a size into BBSizes to align it properly with the (newly
685 // renumbered) block numbers.
686 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
688 // Likewise for BBOffsets.
689 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
691 // Next, update WaterList. Specifically, we need to add NewMBB as having
692 // available water after it.
694 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
696 WaterList.insert(IP, NewBB);
700 /// Split the basic block containing MI into two blocks, which are joined by
701 /// an unconditional branch. Update data structures and renumber blocks to
702 /// account for this change and returns the newly created block.
703 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
704 MachineBasicBlock *OrigBB = MI->getParent();
705 MachineFunction &MF = *OrigBB->getParent();
707 // Create a new MBB for the code after the OrigBB.
708 MachineBasicBlock *NewBB =
709 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
710 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
711 MF.insert(MBBI, NewBB);
713 // Splice the instructions starting with MI over to NewBB.
714 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
716 // Add an unconditional branch from OrigBB to NewBB.
717 // Note the new unconditional branch is not being recorded.
718 // There doesn't seem to be meaningful DebugInfo available; this doesn't
719 // correspond to anything in the source.
720 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
721 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
724 // Update the CFG. All succs of OrigBB are now succs of NewBB.
725 while (!OrigBB->succ_empty()) {
726 MachineBasicBlock *Succ = *OrigBB->succ_begin();
727 OrigBB->removeSuccessor(Succ);
728 NewBB->addSuccessor(Succ);
730 // This pass should be run after register allocation, so there should be no
731 // PHI nodes to update.
732 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
733 && "PHI nodes should be eliminated by now!");
736 // OrigBB branches to NewBB.
737 OrigBB->addSuccessor(NewBB);
739 // Update internal data structures to account for the newly inserted MBB.
740 // This is almost the same as UpdateForInsertedWaterBlock, except that
741 // the Water goes after OrigBB, not NewBB.
742 MF.RenumberBlocks(NewBB);
744 // Insert a size into BBSizes to align it properly with the (newly
745 // renumbered) block numbers.
746 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
748 // Likewise for BBOffsets.
749 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
751 // Next, update WaterList. Specifically, we need to add OrigMBB as having
752 // available water after it (but not if it's already there, which happens
753 // when splitting before a conditional branch that is followed by an
754 // unconditional branch - in that case we want to insert NewBB).
756 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
758 MachineBasicBlock* WaterBB = *IP;
759 if (WaterBB == OrigBB)
760 WaterList.insert(next(IP), NewBB);
762 WaterList.insert(IP, OrigBB);
763 NewWaterList.insert(OrigBB);
765 // Figure out how large the first NewMBB is. (It cannot
766 // contain a constpool_entry or tablejump.)
767 unsigned NewBBSize = 0;
768 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
770 NewBBSize += TII->GetInstSizeInBytes(I);
772 unsigned OrigBBI = OrigBB->getNumber();
773 unsigned NewBBI = NewBB->getNumber();
774 // Set the size of NewBB in BBSizes.
775 BBSizes[NewBBI] = NewBBSize;
777 // We removed instructions from UserMBB, subtract that off from its size.
778 // Add 2 or 4 to the block to count the unconditional branch we added to it.
779 int delta = isThumb1 ? 2 : 4;
780 BBSizes[OrigBBI] -= NewBBSize - delta;
782 // ...and adjust BBOffsets for NewBB accordingly.
783 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
785 // All BBOffsets following these blocks must be modified.
786 AdjustBBOffsetsAfter(NewBB, delta);
791 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
792 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
793 /// constant pool entry).
794 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
795 unsigned TrialOffset, unsigned MaxDisp,
796 bool NegativeOK, bool IsSoImm) {
797 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
798 // purposes of the displacement computation; compensate for that here.
799 // Effectively, the valid range of displacements is 2 bytes smaller for such
801 unsigned TotalAdj = 0;
802 if (isThumb && UserOffset%4 !=0) {
806 // CPEs will be rounded up to a multiple of 4.
807 if (isThumb && TrialOffset%4 != 0) {
812 // In Thumb2 mode, later branch adjustments can shift instructions up and
813 // cause alignment change. In the worst case scenario this can cause the
814 // user's effective address to be subtracted by 2 and the CPE's address to
816 if (isThumb2 && TotalAdj != 4)
817 MaxDisp -= (4 - TotalAdj);
819 if (UserOffset <= TrialOffset) {
820 // User before the Trial.
821 if (TrialOffset - UserOffset <= MaxDisp)
823 // FIXME: Make use full range of soimm values.
824 } else if (NegativeOK) {
825 if (UserOffset - TrialOffset <= MaxDisp)
827 // FIXME: Make use full range of soimm values.
832 /// WaterIsInRange - Returns true if a CPE placed after the specified
833 /// Water (a basic block) will be in range for the specific MI.
835 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
836 MachineBasicBlock* Water, CPUser &U) {
837 unsigned MaxDisp = U.MaxDisp;
838 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
839 BBSizes[Water->getNumber()];
841 // If the CPE is to be inserted before the instruction, that will raise
842 // the offset of the instruction.
843 if (CPEOffset < UserOffset)
844 UserOffset += U.CPEMI->getOperand(2).getImm();
846 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
849 /// CPEIsInRange - Returns true if the distance between specific MI and
850 /// specific ConstPool entry instruction can fit in MI's displacement field.
851 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
852 MachineInstr *CPEMI, unsigned MaxDisp,
853 bool NegOk, bool DoDump) {
854 unsigned CPEOffset = GetOffsetOf(CPEMI);
855 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
858 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
859 << " max delta=" << MaxDisp
860 << " insn address=" << UserOffset
861 << " CPE address=" << CPEOffset
862 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
865 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
869 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
870 /// unconditionally branches to its only successor.
871 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
872 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
875 MachineBasicBlock *Succ = *MBB->succ_begin();
876 MachineBasicBlock *Pred = *MBB->pred_begin();
877 MachineInstr *PredMI = &Pred->back();
878 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
879 || PredMI->getOpcode() == ARM::t2B)
880 return PredMI->getOperand(0).getMBB() == Succ;
885 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
887 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
888 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
890 BBOffsets[i] += delta;
891 // If some existing blocks have padding, adjust the padding as needed, a
892 // bit tricky. delta can be negative so don't use % on that.
895 MachineBasicBlock *MBB = MBBI;
896 if (!MBB->empty() && !HasInlineAsm) {
897 // Constant pool entries require padding.
898 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
899 unsigned OldOffset = BBOffsets[i] - delta;
900 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
904 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
905 // remove existing padding
910 // Thumb1 jump tables require padding. They should be at the end;
911 // following unconditional branches are removed by AnalyzeBranch.
912 MachineInstr *ThumbJTMI = prior(MBB->end());
913 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
914 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
915 unsigned OldMIOffset = NewMIOffset - delta;
916 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
917 // remove existing padding
920 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
933 /// DecrementOldEntry - find the constant pool entry with index CPI
934 /// and instruction CPEMI, and decrement its refcount. If the refcount
935 /// becomes 0 remove the entry and instruction. Returns true if we removed
936 /// the entry, false if we didn't.
938 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
939 // Find the old entry. Eliminate it if it is no longer used.
940 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
941 assert(CPE && "Unexpected!");
942 if (--CPE->RefCount == 0) {
943 RemoveDeadCPEMI(CPEMI);
951 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
952 /// if not, see if an in-range clone of the CPE is in range, and if so,
953 /// change the data structures so the user references the clone. Returns:
954 /// 0 = no existing entry found
955 /// 1 = entry found, and there were no code insertions or deletions
956 /// 2 = entry found, and there were code insertions or deletions
957 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
959 MachineInstr *UserMI = U.MI;
960 MachineInstr *CPEMI = U.CPEMI;
962 // Check to see if the CPE is already in-range.
963 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
964 DEBUG(errs() << "In range\n");
968 // No. Look for previously created clones of the CPE that are in range.
969 unsigned CPI = CPEMI->getOperand(1).getIndex();
970 std::vector<CPEntry> &CPEs = CPEntries[CPI];
971 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
972 // We already tried this one
973 if (CPEs[i].CPEMI == CPEMI)
975 // Removing CPEs can leave empty entries, skip
976 if (CPEs[i].CPEMI == NULL)
978 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
979 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
980 << CPEs[i].CPI << "\n");
981 // Point the CPUser node to the replacement
982 U.CPEMI = CPEs[i].CPEMI;
983 // Change the CPI in the instruction operand to refer to the clone.
984 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
985 if (UserMI->getOperand(j).isCPI()) {
986 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
989 // Adjust the refcount of the clone...
991 // ...and the original. If we didn't remove the old entry, none of the
992 // addresses changed, so we don't need another pass.
993 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
999 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1000 /// the specific unconditional branch instruction.
1001 static inline unsigned getUnconditionalBrDisp(int Opc) {
1004 return ((1<<10)-1)*2;
1006 return ((1<<23)-1)*2;
1011 return ((1<<23)-1)*4;
1014 /// LookForWater - Look for an existing entry in the WaterList in which
1015 /// we can place the CPE referenced from U so it's within range of U's MI.
1016 /// Returns true if found, false if not. If it returns true, WaterIter
1017 /// is set to the WaterList entry. For Thumb, prefer water that will not
1018 /// introduce padding to water that will. To ensure that this pass
1019 /// terminates, the CPE location for a particular CPUser is only allowed to
1020 /// move to a lower address, so search backward from the end of the list and
1021 /// prefer the first water that is in range.
1022 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1023 water_iterator &WaterIter) {
1024 if (WaterList.empty())
1027 bool FoundWaterThatWouldPad = false;
1028 water_iterator IPThatWouldPad;
1029 for (water_iterator IP = prior(WaterList.end()),
1030 B = WaterList.begin();; --IP) {
1031 MachineBasicBlock* WaterBB = *IP;
1032 // Check if water is in range and is either at a lower address than the
1033 // current "high water mark" or a new water block that was created since
1034 // the previous iteration by inserting an unconditional branch. In the
1035 // latter case, we want to allow resetting the high water mark back to
1036 // this new water since we haven't seen it before. Inserting branches
1037 // should be relatively uncommon and when it does happen, we want to be
1038 // sure to take advantage of it for all the CPEs near that block, so that
1039 // we don't insert more branches than necessary.
1040 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1041 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1042 NewWaterList.count(WaterBB))) {
1043 unsigned WBBId = WaterBB->getNumber();
1045 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1046 // This is valid Water, but would introduce padding. Remember
1047 // it in case we don't find any Water that doesn't do this.
1048 if (!FoundWaterThatWouldPad) {
1049 FoundWaterThatWouldPad = true;
1050 IPThatWouldPad = IP;
1060 if (FoundWaterThatWouldPad) {
1061 WaterIter = IPThatWouldPad;
1067 /// CreateNewWater - No existing WaterList entry will work for
1068 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1069 /// block is used if in range, and the conditional branch munged so control
1070 /// flow is correct. Otherwise the block is split to create a hole with an
1071 /// unconditional branch around it. In either case NewMBB is set to a
1072 /// block following which the new island can be inserted (the WaterList
1073 /// is not adjusted).
1074 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1075 unsigned UserOffset,
1076 MachineBasicBlock *&NewMBB) {
1077 CPUser &U = CPUsers[CPUserIndex];
1078 MachineInstr *UserMI = U.MI;
1079 MachineInstr *CPEMI = U.CPEMI;
1080 MachineBasicBlock *UserMBB = UserMI->getParent();
1081 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1082 BBSizes[UserMBB->getNumber()];
1083 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1085 // If the block does not end in an unconditional branch already, and if the
1086 // end of the block is within range, make new water there. (The addition
1087 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1088 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1089 // inside OffsetIsInRange.
1090 if (BBHasFallthrough(UserMBB) &&
1091 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1092 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1093 DEBUG(errs() << "Split at end of block\n");
1094 if (&UserMBB->back() == UserMI)
1095 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1096 NewMBB = next(MachineFunction::iterator(UserMBB));
1097 // Add an unconditional branch from UserMBB to fallthrough block.
1098 // Record it for branch lengthening; this new branch will not get out of
1099 // range, but if the preceding conditional branch is out of range, the
1100 // targets will be exchanged, and the altered branch may be out of
1101 // range, so the machinery has to know about it.
1102 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1103 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1104 TII->get(UncondBr)).addMBB(NewMBB);
1105 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1106 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1107 MaxDisp, false, UncondBr));
1108 int delta = isThumb1 ? 2 : 4;
1109 BBSizes[UserMBB->getNumber()] += delta;
1110 AdjustBBOffsetsAfter(UserMBB, delta);
1112 // What a big block. Find a place within the block to split it.
1113 // This is a little tricky on Thumb1 since instructions are 2 bytes
1114 // and constant pool entries are 4 bytes: if instruction I references
1115 // island CPE, and instruction I+1 references CPE', it will
1116 // not work well to put CPE as far forward as possible, since then
1117 // CPE' cannot immediately follow it (that location is 2 bytes
1118 // farther away from I+1 than CPE was from I) and we'd need to create
1119 // a new island. So, we make a first guess, then walk through the
1120 // instructions between the one currently being looked at and the
1121 // possible insertion point, and make sure any other instructions
1122 // that reference CPEs will be able to use the same island area;
1123 // if not, we back up the insertion point.
1125 // The 4 in the following is for the unconditional branch we'll be
1126 // inserting (allows for long branch on Thumb1). Alignment of the
1127 // island is handled inside OffsetIsInRange.
1128 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1129 // This could point off the end of the block if we've already got
1130 // constant pool entries following this block; only the last one is
1131 // in the water list. Back past any possible branches (allow for a
1132 // conditional and a maximally long unconditional).
1133 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1134 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1136 unsigned EndInsertOffset = BaseInsertOffset +
1137 CPEMI->getOperand(2).getImm();
1138 MachineBasicBlock::iterator MI = UserMI;
1140 unsigned CPUIndex = CPUserIndex+1;
1141 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1142 Offset < BaseInsertOffset;
1143 Offset += TII->GetInstSizeInBytes(MI),
1145 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1146 CPUser &U = CPUsers[CPUIndex];
1147 if (!OffsetIsInRange(Offset, EndInsertOffset,
1148 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1149 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1150 EndInsertOffset -= (isThumb1 ? 2 : 4);
1152 // This is overly conservative, as we don't account for CPEMIs
1153 // being reused within the block, but it doesn't matter much.
1154 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1158 DEBUG(errs() << "Split in middle of big block\n");
1159 NewMBB = SplitBlockBeforeInstr(prior(MI));
1163 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1164 /// is out-of-range. If so, pick up the constant pool value and move it some
1165 /// place in-range. Return true if we changed any addresses (thus must run
1166 /// another pass of branch lengthening), false otherwise.
1167 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1168 unsigned CPUserIndex) {
1169 CPUser &U = CPUsers[CPUserIndex];
1170 MachineInstr *UserMI = U.MI;
1171 MachineInstr *CPEMI = U.CPEMI;
1172 unsigned CPI = CPEMI->getOperand(1).getIndex();
1173 unsigned Size = CPEMI->getOperand(2).getImm();
1174 // Compute this only once, it's expensive. The 4 or 8 is the value the
1175 // hardware keeps in the PC.
1176 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1178 // See if the current entry is within range, or there is a clone of it
1180 int result = LookForExistingCPEntry(U, UserOffset);
1181 if (result==1) return false;
1182 else if (result==2) return true;
1184 // No existing clone of this CPE is within range.
1185 // We will be generating a new clone. Get a UID for it.
1186 unsigned ID = AFI->createConstPoolEntryUId();
1188 // Look for water where we can place this CPE.
1189 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1190 MachineBasicBlock *NewMBB;
1192 if (LookForWater(U, UserOffset, IP)) {
1193 DEBUG(errs() << "found water in range\n");
1194 MachineBasicBlock *WaterBB = *IP;
1196 // If the original WaterList entry was "new water" on this iteration,
1197 // propagate that to the new island. This is just keeping NewWaterList
1198 // updated to match the WaterList, which will be updated below.
1199 if (NewWaterList.count(WaterBB)) {
1200 NewWaterList.erase(WaterBB);
1201 NewWaterList.insert(NewIsland);
1203 // The new CPE goes before the following block (NewMBB).
1204 NewMBB = next(MachineFunction::iterator(WaterBB));
1208 DEBUG(errs() << "No water found\n");
1209 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1211 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1212 // called while handling branches so that the water will be seen on the
1213 // next iteration for constant pools, but in this context, we don't want
1214 // it. Check for this so it will be removed from the WaterList.
1215 // Also remove any entry from NewWaterList.
1216 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1217 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1218 if (IP != WaterList.end())
1219 NewWaterList.erase(WaterBB);
1221 // We are adding new water. Update NewWaterList.
1222 NewWaterList.insert(NewIsland);
1225 // Remove the original WaterList entry; we want subsequent insertions in
1226 // this vicinity to go after the one we're about to insert. This
1227 // considerably reduces the number of times we have to move the same CPE
1228 // more than once and is also important to ensure the algorithm terminates.
1229 if (IP != WaterList.end())
1230 WaterList.erase(IP);
1232 // Okay, we know we can put an island before NewMBB now, do it!
1233 MF.insert(NewMBB, NewIsland);
1235 // Update internal data structures to account for the newly inserted MBB.
1236 UpdateForInsertedWaterBlock(NewIsland);
1238 // Decrement the old entry, and remove it if refcount becomes 0.
1239 DecrementOldEntry(CPI, CPEMI);
1241 // Now that we have an island to add the CPE to, clone the original CPE and
1242 // add it to the island.
1243 U.HighWaterMark = NewIsland;
1244 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1245 TII->get(ARM::CONSTPOOL_ENTRY))
1246 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1247 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1250 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1251 // Compensate for .align 2 in thumb mode.
1252 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
1254 // Increase the size of the island block to account for the new entry.
1255 BBSizes[NewIsland->getNumber()] += Size;
1256 AdjustBBOffsetsAfter(NewIsland, Size);
1258 // Finally, change the CPI in the instruction operand to be ID.
1259 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1260 if (UserMI->getOperand(i).isCPI()) {
1261 UserMI->getOperand(i).setIndex(ID);
1265 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1266 << '\t' << *UserMI);
1271 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1272 /// sizes and offsets of impacted basic blocks.
1273 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1274 MachineBasicBlock *CPEBB = CPEMI->getParent();
1275 unsigned Size = CPEMI->getOperand(2).getImm();
1276 CPEMI->eraseFromParent();
1277 BBSizes[CPEBB->getNumber()] -= Size;
1278 // All succeeding offsets have the current size value added in, fix this.
1279 if (CPEBB->empty()) {
1280 // In thumb1 mode, the size of island may be padded by two to compensate for
1281 // the alignment requirement. Then it will now be 2 when the block is
1282 // empty, so fix this.
1283 // All succeeding offsets have the current size value added in, fix this.
1284 if (BBSizes[CPEBB->getNumber()] != 0) {
1285 Size += BBSizes[CPEBB->getNumber()];
1286 BBSizes[CPEBB->getNumber()] = 0;
1289 AdjustBBOffsetsAfter(CPEBB, -Size);
1290 // An island has only one predecessor BB and one successor BB. Check if
1291 // this BB's predecessor jumps directly to this BB's successor. This
1292 // shouldn't happen currently.
1293 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1294 // FIXME: remove the empty blocks after all the work is done?
1297 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1299 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1300 unsigned MadeChange = false;
1301 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1302 std::vector<CPEntry> &CPEs = CPEntries[i];
1303 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1304 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1305 RemoveDeadCPEMI(CPEs[j].CPEMI);
1306 CPEs[j].CPEMI = NULL;
1314 /// BBIsInRange - Returns true if the distance between specific MI and
1315 /// specific BB can fit in MI's displacement field.
1316 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1318 unsigned PCAdj = isThumb ? 4 : 8;
1319 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1320 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1322 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1323 << " from BB#" << MI->getParent()->getNumber()
1324 << " max delta=" << MaxDisp
1325 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1326 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1328 if (BrOffset <= DestOffset) {
1329 // Branch before the Dest.
1330 if (DestOffset-BrOffset <= MaxDisp)
1333 if (BrOffset-DestOffset <= MaxDisp)
1339 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1340 /// away to fit in its displacement field.
1341 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1342 MachineInstr *MI = Br.MI;
1343 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1345 // Check to see if the DestBB is already in-range.
1346 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1350 return FixUpUnconditionalBr(MF, Br);
1351 return FixUpConditionalBr(MF, Br);
1354 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1355 /// too far away to fit in its displacement field. If the LR register has been
1356 /// spilled in the epilogue, then we can use BL to implement a far jump.
1357 /// Otherwise, add an intermediate branch instruction to a branch.
1359 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1360 MachineInstr *MI = Br.MI;
1361 MachineBasicBlock *MBB = MI->getParent();
1363 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1365 // Use BL to implement far jump.
1366 Br.MaxDisp = (1 << 21) * 2;
1367 MI->setDesc(TII->get(ARM::tBfar));
1368 BBSizes[MBB->getNumber()] += 2;
1369 AdjustBBOffsetsAfter(MBB, 2);
1373 DEBUG(errs() << " Changed B to long jump " << *MI);
1378 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1379 /// far away to fit in its displacement field. It is converted to an inverse
1380 /// conditional branch + an unconditional branch to the destination.
1382 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1383 MachineInstr *MI = Br.MI;
1384 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1386 // Add an unconditional branch to the destination and invert the branch
1387 // condition to jump over it:
1393 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1394 CC = ARMCC::getOppositeCondition(CC);
1395 unsigned CCReg = MI->getOperand(2).getReg();
1397 // If the branch is at the end of its MBB and that has a fall-through block,
1398 // direct the updated conditional branch to the fall-through block. Otherwise,
1399 // split the MBB before the next instruction.
1400 MachineBasicBlock *MBB = MI->getParent();
1401 MachineInstr *BMI = &MBB->back();
1402 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1406 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1407 BMI->getOpcode() == Br.UncondBr) {
1408 // Last MI in the BB is an unconditional branch. Can we simply invert the
1409 // condition and swap destinations:
1415 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1416 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1417 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1419 BMI->getOperand(0).setMBB(DestBB);
1420 MI->getOperand(0).setMBB(NewDest);
1421 MI->getOperand(1).setImm(CC);
1428 SplitBlockBeforeInstr(MI);
1429 // No need for the branch to the next block. We're adding an unconditional
1430 // branch to the destination.
1431 int delta = TII->GetInstSizeInBytes(&MBB->back());
1432 BBSizes[MBB->getNumber()] -= delta;
1433 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1434 AdjustBBOffsetsAfter(SplitBB, -delta);
1435 MBB->back().eraseFromParent();
1436 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1438 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1440 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1441 << " also invert condition and change dest. to BB#"
1442 << NextBB->getNumber() << "\n");
1444 // Insert a new conditional branch and a new unconditional branch.
1445 // Also update the ImmBranch as well as adding a new entry for the new branch.
1446 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1447 TII->get(MI->getOpcode()))
1448 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1449 Br.MI = &MBB->back();
1450 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1451 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1452 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1453 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1454 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1456 // Remove the old conditional branch. It may or may not still be in MBB.
1457 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1458 MI->eraseFromParent();
1460 // The net size change is an addition of one unconditional branch.
1461 int delta = TII->GetInstSizeInBytes(&MBB->back());
1462 AdjustBBOffsetsAfter(MBB, delta);
1466 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1467 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1468 /// to do this if tBfar is not used.
1469 bool ARMConstantIslands::UndoLRSpillRestore() {
1470 bool MadeChange = false;
1471 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1472 MachineInstr *MI = PushPopMIs[i];
1473 // First two operands are predicates, the third is a zero since there
1475 if (MI->getOpcode() == ARM::tPOP_RET &&
1476 MI->getOperand(3).getReg() == ARM::PC &&
1477 MI->getNumExplicitOperands() == 4) {
1478 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1479 MI->eraseFromParent();
1486 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1487 bool MadeChange = false;
1489 // Shrink ADR and LDR from constantpool.
1490 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1491 CPUser &U = CPUsers[i];
1492 unsigned Opcode = U.MI->getOpcode();
1493 unsigned NewOpc = 0;
1498 case ARM::t2LEApcrel:
1499 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1500 NewOpc = ARM::tLEApcrel;
1506 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1507 NewOpc = ARM::tLDRpci;
1517 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1518 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1519 // FIXME: Check if offset is multiple of scale if scale is not 4.
1520 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1521 U.MI->setDesc(TII->get(NewOpc));
1522 MachineBasicBlock *MBB = U.MI->getParent();
1523 BBSizes[MBB->getNumber()] -= 2;
1524 AdjustBBOffsetsAfter(MBB, -2);
1530 MadeChange |= OptimizeThumb2Branches(MF);
1531 MadeChange |= OptimizeThumb2JumpTables(MF);
1535 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1536 bool MadeChange = false;
1538 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1539 ImmBranch &Br = ImmBranches[i];
1540 unsigned Opcode = Br.MI->getOpcode();
1541 unsigned NewOpc = 0;
1559 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1560 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1561 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1562 Br.MI->setDesc(TII->get(NewOpc));
1563 MachineBasicBlock *MBB = Br.MI->getParent();
1564 BBSizes[MBB->getNumber()] -= 2;
1565 AdjustBBOffsetsAfter(MBB, -2);
1571 Opcode = Br.MI->getOpcode();
1572 if (Opcode != ARM::tBcc)
1576 unsigned PredReg = 0;
1577 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1578 if (Pred == ARMCC::EQ)
1580 else if (Pred == ARMCC::NE)
1581 NewOpc = ARM::tCBNZ;
1584 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1585 // Check if the distance is within 126. Subtract starting offset by 2
1586 // because the cmp will be eliminated.
1587 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1588 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1589 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1590 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1591 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1592 unsigned Reg = CmpMI->getOperand(0).getReg();
1593 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1594 if (Pred == ARMCC::AL &&
1595 CmpMI->getOperand(1).getImm() == 0 &&
1596 isARMLowRegister(Reg)) {
1597 MachineBasicBlock *MBB = Br.MI->getParent();
1598 MachineInstr *NewBR =
1599 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1600 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1601 CmpMI->eraseFromParent();
1602 Br.MI->eraseFromParent();
1604 BBSizes[MBB->getNumber()] -= 2;
1605 AdjustBBOffsetsAfter(MBB, -2);
1616 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1617 /// jumptables when it's possible.
1618 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1619 bool MadeChange = false;
1621 // FIXME: After the tables are shrunk, can we get rid some of the
1622 // constantpool tables?
1623 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1624 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1625 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1626 MachineInstr *MI = T2JumpTables[i];
1627 const TargetInstrDesc &TID = MI->getDesc();
1628 unsigned NumOps = TID.getNumOperands();
1629 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1630 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1631 unsigned JTI = JTOP.getIndex();
1632 assert(JTI < JT.size());
1635 bool HalfWordOk = true;
1636 unsigned JTOffset = GetOffsetOf(MI) + 4;
1637 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1638 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1639 MachineBasicBlock *MBB = JTBBs[j];
1640 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1641 // Negative offset is not ok. FIXME: We should change BB layout to make
1642 // sure all the branches are forward.
1643 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1645 unsigned TBHLimit = ((1<<16)-1)*2;
1646 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1648 if (!ByteOk && !HalfWordOk)
1652 if (ByteOk || HalfWordOk) {
1653 MachineBasicBlock *MBB = MI->getParent();
1654 unsigned BaseReg = MI->getOperand(0).getReg();
1655 bool BaseRegKill = MI->getOperand(0).isKill();
1658 unsigned IdxReg = MI->getOperand(1).getReg();
1659 bool IdxRegKill = MI->getOperand(1).isKill();
1660 MachineBasicBlock::iterator PrevI = MI;
1661 if (PrevI == MBB->begin())
1664 MachineInstr *AddrMI = --PrevI;
1666 // Examine the instruction that calculate the jumptable entry address.
1667 // If it's not the one just before the t2BR_JT, we won't delete it, then
1668 // it's not worth doing the optimization.
1669 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1670 const MachineOperand &MO = AddrMI->getOperand(k);
1671 if (!MO.isReg() || !MO.getReg())
1673 if (MO.isDef() && MO.getReg() != BaseReg) {
1677 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1685 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1686 // to delete it as well.
1687 MachineInstr *LeaMI = --PrevI;
1688 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1689 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1690 LeaMI->getOperand(0).getReg() != BaseReg)
1696 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1697 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1698 .addReg(IdxReg, getKillRegState(IdxRegKill))
1699 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1700 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1701 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1702 // is 2-byte aligned. For now, asm printer will fix it up.
1703 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1704 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1705 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1706 OrigSize += TII->GetInstSizeInBytes(MI);
1708 AddrMI->eraseFromParent();
1709 LeaMI->eraseFromParent();
1710 MI->eraseFromParent();
1712 int delta = OrigSize - NewSize;
1713 BBSizes[MBB->getNumber()] -= delta;
1714 AdjustBBOffsetsAfter(MBB, -delta);
1724 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1725 /// jump tables always branch forwards, since that's what tbb and tbh need.
1726 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1727 bool MadeChange = false;
1729 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1730 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1731 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1732 MachineInstr *MI = T2JumpTables[i];
1733 const TargetInstrDesc &TID = MI->getDesc();
1734 unsigned NumOps = TID.getNumOperands();
1735 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1736 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1737 unsigned JTI = JTOP.getIndex();
1738 assert(JTI < JT.size());
1740 // We prefer if target blocks for the jump table come after the jump
1741 // instruction so we can use TB[BH]. Loop through the target blocks
1742 // and try to adjust them such that that's true.
1743 int JTNumber = MI->getParent()->getNumber();
1744 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1745 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1746 MachineBasicBlock *MBB = JTBBs[j];
1747 int DTNumber = MBB->getNumber();
1749 if (DTNumber < JTNumber) {
1750 // The destination precedes the switch. Try to move the block forward
1751 // so we have a positive offset.
1752 MachineBasicBlock *NewBB =
1753 AdjustJTTargetBlockForward(MBB, MI->getParent());
1755 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1764 MachineBasicBlock *ARMConstantIslands::
1765 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1767 MachineFunction &MF = *BB->getParent();
1769 // If it's the destination block is terminated by an unconditional branch,
1770 // try to move it; otherwise, create a new block following the jump
1771 // table that branches back to the actual target. This is a very simple
1772 // heuristic. FIXME: We can definitely improve it.
1773 MachineBasicBlock *TBB = 0, *FBB = 0;
1774 SmallVector<MachineOperand, 4> Cond;
1775 SmallVector<MachineOperand, 4> CondPrior;
1776 MachineFunction::iterator BBi = BB;
1777 MachineFunction::iterator OldPrior = prior(BBi);
1779 // If the block terminator isn't analyzable, don't try to move the block
1780 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1782 // If the block ends in an unconditional branch, move it. The prior block
1783 // has to have an analyzable terminator for us to move this one. Be paranoid
1784 // and make sure we're not trying to move the entry block of the function.
1785 if (!B && Cond.empty() && BB != MF.begin() &&
1786 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1787 BB->moveAfter(JTBB);
1788 OldPrior->updateTerminator();
1789 BB->updateTerminator();
1790 // Update numbering to account for the block being moved.
1791 MF.RenumberBlocks();
1796 // Create a new MBB for the code after the jump BB.
1797 MachineBasicBlock *NewBB =
1798 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1799 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1800 MF.insert(MBBI, NewBB);
1802 // Add an unconditional branch from NewBB to BB.
1803 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1804 // correspond directly to anything in the source.
1805 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1806 BuildMI(NewBB, DebugLoc::getUnknownLoc(), TII->get(ARM::t2B)).addMBB(BB);
1808 // Update internal data structures to account for the newly inserted MBB.
1809 MF.RenumberBlocks(NewBB);
1812 NewBB->addSuccessor(BB);
1813 JTBB->removeSuccessor(BB);
1814 JTBB->addSuccessor(NewBB);