1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // Substantial modifications by Evan Cheng and Dale Johannesen.
9 //===----------------------------------------------------------------------===//
11 // This file contains a pass that splits the constant pool up into 'islands'
12 // which are scattered through-out the function. This is required due to the
13 // limited pc-relative displacements that ARM has.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "arm-cp-islands"
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/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
33 STATISTIC(NumCPEs, "Number of constpool entries");
34 STATISTIC(NumSplit, "Number of uncond branches inserted");
35 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
36 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
40 /// requires constant pool entries to be scattered among the instructions
41 /// inside a function. To do this, it completely ignores the normal LLVM
42 /// constant pool; instead, it places constants wherever it feels like with
43 /// special instructions.
45 /// The terminology used in this pass includes:
46 /// Islands - Clumps of constants placed in the function.
47 /// Water - Potential places where an island could be formed.
48 /// CPE - A constant pool entry that has been placed somewhere, which
49 /// tracks a list of users.
50 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
51 /// NextUID - Assign unique ID's to CPE's.
54 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
56 std::vector<unsigned> BBSizes;
58 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
59 std::vector<unsigned> BBOffsets;
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;
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.
73 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
77 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
79 std::vector<CPUser> CPUsers;
81 /// 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.
88 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
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;
99 /// 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
105 unsigned MaxDisp : 31;
108 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
112 /// Branches - Keep track of all the immediate branch instructions.
114 std::vector<ImmBranch> ImmBranches;
116 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
118 SmallVector<MachineInstr*, 4> PushPopMIs;
120 /// HasFarJump - True if any far jump instruction has been emitted during
121 /// the branch fix up pass.
124 const TargetInstrInfo *TII;
125 const ARMFunctionInfo *AFI;
127 virtual bool runOnMachineFunction(MachineFunction &Fn);
129 virtual const char *getPassName() const {
130 return "ARM constant island placement and branch shortening pass";
134 void DoInitialPlacement(MachineFunction &Fn,
135 std::vector<MachineInstr*> &CPEMIs);
136 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
137 void InitialFunctionScan(MachineFunction &Fn,
138 const std::vector<MachineInstr*> &CPEMIs);
139 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
140 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
141 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
142 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
143 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
144 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
145 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
146 MachineInstr *CPEMI, unsigned Disp,
148 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
150 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
151 unsigned Disp, bool NegativeOK);
152 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
153 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
154 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
155 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
156 bool UndoLRSpillRestore();
158 unsigned GetOffsetOf(MachineInstr *MI) const;
162 /// createARMConstantIslandPass - returns an instance of the constpool
164 FunctionPass *llvm::createARMConstantIslandPass() {
165 return new ARMConstantIslands();
168 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
169 MachineConstantPool &MCP = *Fn.getConstantPool();
171 TII = Fn.getTarget().getInstrInfo();
172 AFI = Fn.getInfo<ARMFunctionInfo>();
176 // Renumber all of the machine basic blocks in the function, guaranteeing that
177 // the numbers agree with the position of the block in the function.
180 // Perform the initial placement of the constant pool entries. To start with,
181 // we put them all at the end of the function.
182 std::vector<MachineInstr*> CPEMIs;
184 DoInitialPlacement(Fn, CPEMIs);
186 /// The next UID to take is the first unused one.
187 NextUID = CPEMIs.size();
189 // Do the initial scan of the function, building up information about the
190 // sizes of each block, the location of all the water, and finding all of the
191 // constant pool users.
192 InitialFunctionScan(Fn, CPEMIs);
195 // Iteratively place constant pool entries and fix up branches until there
197 bool MadeChange = false;
200 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
201 Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
202 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
203 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
209 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
210 // Undo the spill / restore of LR if possible.
211 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
212 MadeChange |= UndoLRSpillRestore();
225 /// DoInitialPlacement - Perform the initial placement of the constant pool
226 /// entries. To start with, we put them all at the end of the function.
227 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
228 std::vector<MachineInstr*> &CPEMIs){
229 // Create the basic block to hold the CPE's.
230 MachineBasicBlock *BB = new MachineBasicBlock();
231 Fn.getBasicBlockList().push_back(BB);
233 // Add all of the constants from the constant pool to the end block, use an
234 // identity mapping of CPI's to CPE's.
235 const std::vector<MachineConstantPoolEntry> &CPs =
236 Fn.getConstantPool()->getConstants();
238 const TargetData &TD = *Fn.getTarget().getTargetData();
239 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
240 unsigned Size = TD.getTypeSize(CPs[i].getType());
241 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
242 // we would have to pad them out or something so that instructions stay
244 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
245 MachineInstr *CPEMI =
246 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
247 .addImm(i).addConstantPoolIndex(i).addImm(Size);
248 CPEMIs.push_back(CPEMI);
250 // Add a new CPEntry, but no corresponding CPUser yet.
251 std::vector<CPEntry> CPEs;
252 CPEs.push_back(CPEntry(CPEMI, i));
253 CPEntries.push_back(CPEs);
255 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
259 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
260 /// into the block immediately after it.
261 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
262 // Get the next machine basic block in the function.
263 MachineFunction::iterator MBBI = MBB;
264 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
267 MachineBasicBlock *NextBB = next(MBBI);
268 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
269 E = MBB->succ_end(); I != E; ++I)
276 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
277 /// look up the corresponding CPEntry.
278 ARMConstantIslands::CPEntry
279 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
280 const MachineInstr *CPEMI) {
281 std::vector<CPEntry> &CPEs = CPEntries[CPI];
282 // Number of entries per constpool index should be small, just do a
284 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
285 if (CPEs[i].CPEMI == CPEMI)
291 /// InitialFunctionScan - Do the initial scan of the function, building up
292 /// information about the sizes of each block, the location of all the water,
293 /// and finding all of the constant pool users.
294 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
295 const std::vector<MachineInstr*> &CPEMIs) {
297 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
299 MachineBasicBlock &MBB = *MBBI;
301 // If this block doesn't fall through into the next MBB, then this is
302 // 'water' that a constant pool island could be placed.
303 if (!BBHasFallthrough(&MBB))
304 WaterList.push_back(&MBB);
306 unsigned MBBSize = 0;
307 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
309 // Add instruction size to MBBSize.
310 MBBSize += ARM::GetInstSize(I);
312 int Opc = I->getOpcode();
313 if (TII->isBranch(Opc)) {
320 continue; // Ignore JT branches
341 // Record this immediate branch.
342 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
343 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
346 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
347 PushPopMIs.push_back(I);
349 // Scan the instructions for constant pool operands.
350 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
351 if (I->getOperand(op).isConstantPoolIndex()) {
352 // We found one. The addressing mode tells us the max displacement
353 // from the PC that this instruction permits.
355 // Basic size info comes from the TSFlags field.
358 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
359 switch (TSFlags & ARMII::AddrModeMask) {
361 // Constant pool entries can reach anything.
362 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
364 assert(0 && "Unknown addressing mode for CP reference!");
365 case ARMII::AddrMode1: // AM1: 8 bits << 2
367 Scale = 4; // Taking the address of a CP entry.
369 case ARMII::AddrMode2:
370 Bits = 12; // +-offset_12
372 case ARMII::AddrMode3:
373 Bits = 8; // +-offset_8
375 // addrmode4 has no immediate offset.
376 case ARMII::AddrMode5:
378 Scale = 4; // +-(offset_8*4)
380 case ARMII::AddrModeT1:
381 Bits = 5; // +offset_5
383 case ARMII::AddrModeT2:
385 Scale = 2; // +(offset_5*2)
387 case ARMII::AddrModeT4:
389 Scale = 4; // +(offset_5*4)
391 case ARMII::AddrModeTs:
393 Scale = 4; // +(offset_8*4)
397 // Remember that this is a user of a CP entry.
398 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
399 MachineInstr *CPEMI = CPEMIs[CPI];
400 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
401 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
403 // Increment corresponding CPEntry reference count.
404 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
405 assert(CPE && "Cannot find a corresponding CPEntry!");
408 // Instructions can only use one CP entry, don't bother scanning the
409 // rest of the operands.
414 // In thumb mode, if this block is a constpool island, pessimistically
415 // assume it needs to be padded by two byte so it's aligned on 4 byte
417 if (AFI->isThumbFunction() &&
419 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
422 BBSizes.push_back(MBBSize);
423 BBOffsets.push_back(Offset);
428 /// GetOffsetOf - Return the current offset of the specified machine instruction
429 /// from the start of the function. This offset changes as stuff is moved
430 /// around inside the function.
431 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
432 MachineBasicBlock *MBB = MI->getParent();
434 // The offset is composed of two things: the sum of the sizes of all MBB's
435 // before this instruction's block, and the offset from the start of the block
437 unsigned Offset = BBOffsets[MBB->getNumber()];
439 // Sum instructions before MI in MBB.
440 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
441 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
442 if (&*I == MI) return Offset;
443 Offset += ARM::GetInstSize(I);
447 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
449 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
450 const MachineBasicBlock *RHS) {
451 return LHS->getNumber() < RHS->getNumber();
454 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
455 /// machine function, it upsets all of the block numbers. Renumber the blocks
456 /// and update the arrays that parallel this numbering.
457 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
458 // Renumber the MBB's to keep them consequtive.
459 NewBB->getParent()->RenumberBlocks(NewBB);
461 // Insert a size into BBSizes to align it properly with the (newly
462 // renumbered) block numbers.
463 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
465 // Likewise for BBOffsets.
466 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
468 // Next, update WaterList. Specifically, we need to add NewMBB as having
469 // available water after it.
470 std::vector<MachineBasicBlock*>::iterator IP =
471 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
473 WaterList.insert(IP, NewBB);
477 /// Split the basic block containing MI into two blocks, which are joined by
478 /// an unconditional branch. Update datastructures and renumber blocks to
479 /// account for this change and returns the newly created block.
480 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
481 MachineBasicBlock *OrigBB = MI->getParent();
482 bool isThumb = AFI->isThumbFunction();
484 // Create a new MBB for the code after the OrigBB.
485 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
486 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
487 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
489 // Splice the instructions starting with MI over to NewBB.
490 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
492 // Add an unconditional branch from OrigBB to NewBB.
493 // Note the new unconditional branch is not being recorded.
494 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
497 // Update the CFG. All succs of OrigBB are now succs of NewBB.
498 while (!OrigBB->succ_empty()) {
499 MachineBasicBlock *Succ = *OrigBB->succ_begin();
500 OrigBB->removeSuccessor(Succ);
501 NewBB->addSuccessor(Succ);
503 // This pass should be run after register allocation, so there should be no
504 // PHI nodes to update.
505 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
506 && "PHI nodes should be eliminated by now!");
509 // OrigBB branches to NewBB.
510 OrigBB->addSuccessor(NewBB);
512 // Update internal data structures to account for the newly inserted MBB.
513 // This is almost the same as UpdateForInsertedWaterBlock, except that
514 // the Water goes after OrigBB, not NewBB.
515 NewBB->getParent()->RenumberBlocks(NewBB);
517 // Insert a size into BBSizes to align it properly with the (newly
518 // renumbered) block numbers.
519 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
521 // Likewise for BBOffsets.
522 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
524 // Next, update WaterList. Specifically, we need to add OrigMBB as having
525 // available water after it (but not if it's already there, which happens
526 // when splitting before a conditional branch that is followed by an
527 // unconditional branch - in that case we want to insert NewBB).
528 std::vector<MachineBasicBlock*>::iterator IP =
529 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
531 MachineBasicBlock* WaterBB = *IP;
532 if (WaterBB == OrigBB)
533 WaterList.insert(next(IP), NewBB);
535 WaterList.insert(IP, OrigBB);
537 // Figure out how large the first NewMBB is.
538 unsigned NewBBSize = 0;
539 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
541 NewBBSize += ARM::GetInstSize(I);
543 unsigned OrigBBI = OrigBB->getNumber();
544 unsigned NewBBI = NewBB->getNumber();
545 // Set the size of NewBB in BBSizes.
546 BBSizes[NewBBI] = NewBBSize;
548 // We removed instructions from UserMBB, subtract that off from its size.
549 // Add 2 or 4 to the block to count the unconditional branch we added to it.
550 unsigned delta = isThumb ? 2 : 4;
551 BBSizes[OrigBBI] -= NewBBSize - delta;
553 // ...and adjust BBOffsets for NewBB accordingly.
554 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
556 // All BBOffsets following these blocks must be modified.
557 AdjustBBOffsetsAfter(NewBB, delta);
562 //// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
564 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
565 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
566 if (UserOffset <= TrialOffset) {
567 // User before the Trial.
568 if (TrialOffset-UserOffset <= MaxDisp)
570 } else if (NegativeOK) {
571 if (UserOffset-TrialOffset <= MaxDisp)
577 /// WaterIsInRange - Returns true if a CPE placed after the specified
578 /// Water (a basic block) will be in range for the specific MI.
580 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
581 MachineBasicBlock* Water, unsigned MaxDisp)
583 bool isThumb = AFI->isThumbFunction();
584 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
585 BBSizes[Water->getNumber()];
586 // If the Water is a constpool island, it has already been aligned.
590 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
593 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
596 /// CPEIsInRange - Returns true if the distance between specific MI and
597 /// specific ConstPool entry instruction can fit in MI's displacement field.
598 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
600 unsigned MaxDisp, bool DoDump) {
601 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
602 // in the island adds two byte padding.
603 bool isThumb = AFI->isThumbFunction();
604 unsigned AlignAdj = isThumb ? 2 : 0;
605 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
608 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
609 << " max delta=" << MaxDisp
610 << " insn address=" << UserOffset
611 << " CPE address=" << CPEOffset
612 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
615 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
618 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
619 /// unconditionally branches to its only successor.
620 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
621 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
624 MachineBasicBlock *Succ = *MBB->succ_begin();
625 MachineBasicBlock *Pred = *MBB->pred_begin();
626 MachineInstr *PredMI = &Pred->back();
627 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
628 return PredMI->getOperand(0).getMBB() == Succ;
632 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
634 MachineFunction::iterator MBBI = BB->getParent()->end();
635 for(int i=BB->getNumber()+1; i<=prior(MBBI)->getNumber(); i++)
636 BBOffsets[i] += delta;
639 /// DecrementOldEntry - find the constant pool entry with index CPI
640 /// and instruction CPEMI, and decrement its refcount. If the refcount
641 /// becomes 0 remove the entry and instruction. Returns true if we removed
642 /// the entry, false if we didn't.
644 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI,
646 // Find the old entry. Eliminate it if it is no longer used.
647 CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
648 assert(OldCPE && "Unexpected!");
649 if (--OldCPE->RefCount == 0) {
650 MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
651 if (OldCPEBB->empty()) {
652 // In thumb mode, the size of island is padded by two to compensate for
653 // the alignment requirement. Thus it will now be 2 when the block is
654 // empty, so fix this.
655 // All succeeding offsets have the current size value added in, fix this.
656 if (BBSizes[OldCPEBB->getNumber()] != 0) {
657 AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
658 BBSizes[OldCPEBB->getNumber()] = 0;
660 // An island has only one predecessor BB and one successor BB. Check if
661 // this BB's predecessor jumps directly to this BB's successor. This
662 // shouldn't happen currently.
663 assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
664 // FIXME: remove the empty blocks after all the work is done?
666 BBSizes[OldCPEBB->getNumber()] -= Size;
667 // All succeeding offsets have the current size value added in, fix this.
668 AdjustBBOffsetsAfter(OldCPEBB, -Size);
670 OldCPE->CPEMI->eraseFromParent();
671 OldCPE->CPEMI = NULL;
678 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
679 /// if not, see if an in-range clone of the CPE is in range, and if so,
680 /// change the data structures so the user references the clone. Returns:
681 /// 0 = no existing entry found
682 /// 1 = entry found, and there were no code insertions or deletions
683 /// 2 = entry found, and there were code insertions or deletions
684 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
686 MachineInstr *UserMI = U.MI;
687 MachineInstr *CPEMI = U.CPEMI;
689 // Check to see if the CPE is already in-range.
690 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
691 DOUT << "In range\n";
695 // No. Look for previously created clones of the CPE that are in range.
696 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
697 std::vector<CPEntry> &CPEs = CPEntries[CPI];
698 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
699 // We already tried this one
700 if (CPEs[i].CPEMI == CPEMI)
702 // Removing CPEs can leave empty entries, skip
703 if (CPEs[i].CPEMI == NULL)
705 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
706 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
707 // Point the CPUser node to the replacement
708 U.CPEMI = CPEs[i].CPEMI;
709 // Change the CPI in the instruction operand to refer to the clone.
710 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
711 if (UserMI->getOperand(j).isConstantPoolIndex()) {
712 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
715 // Adjust the refcount of the clone...
717 // ...and the original. If we didn't remove the old entry, none of the
718 // addresses changed, so we don't need another pass.
719 unsigned Size = CPEMI->getOperand(2).getImm();
720 return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
726 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
727 /// is out-of-range. If so, pick it up the constant pool value and move it some
728 /// place in-range. Return true if we changed any addresses (thus must run
729 /// another pass of branch lengthening), false otherwise.
730 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
731 MachineInstr *UserMI = U.MI;
732 MachineInstr *CPEMI = U.CPEMI;
733 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
734 unsigned Size = CPEMI->getOperand(2).getImm();
735 bool isThumb = AFI->isThumbFunction();
736 MachineBasicBlock *NewMBB;
737 // Compute this only once, it's expensive
738 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
740 // See if the current entry is within range, or there is a clone of it
742 int result = LookForExistingCPEntry(U, UserOffset);
743 if (result==1) return false;
744 else if (result==2) return true;
746 // No existing clone of this CPE is within range.
747 // We will be generating a new clone. Get a UID for it.
748 unsigned ID = NextUID++;
750 // Look for water where we can place this CPE. We look for the farthest one
751 // away that will work. Forward references only for now (although later
752 // we might find some that are backwards).
753 bool WaterFound = false;
754 if (!WaterList.empty()) {
755 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
756 B = WaterList.begin();; --IP) {
757 MachineBasicBlock* WaterBB = *IP;
758 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
760 DOUT << "found water in range\n";
761 // CPE goes before following block (NewMBB).
762 NewMBB = next(MachineFunction::iterator(WaterBB));
763 // Remove the original WaterList entry; we want subsequent
764 // insertions in this vicinity to go after the one we're
765 // about to insert. This considerably reduces the number
766 // of times we have to move the same CPE more than once.
778 DOUT << "No water found\n";
779 MachineBasicBlock *UserMBB = UserMI->getParent();
780 unsigned TrialOffset = BBOffsets[UserMBB->getNumber()] +
781 BBSizes[UserMBB->getNumber()] +
782 isThumb ? 2 : 4; /* for branch to be added */
784 // If the use is at the end of the block, or the end of the block
785 // is within range, make new water there. (If the block ends in
786 // an unconditional branch already, it is water, and is known to
787 // be out of range; so it's OK to assume above we'll be adding a Br.)
788 if (&UserMBB->back() == UserMI ||
789 OffsetIsInRange(UserOffset, TrialOffset, U.MaxDisp, !isThumb)) {
790 if (&UserMBB->back() == UserMI)
791 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
792 NewMBB = next(MachineFunction::iterator(UserMBB));
793 // Add an unconditional branch from UserMBB to fallthrough block.
794 // Note the new unconditional branch is not being recorded.
795 BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
796 int delta = isThumb ? 2 : 4;
797 BBSizes[UserMBB->getNumber()] += delta;
798 AdjustBBOffsetsAfter(UserMBB, delta);
800 // What a big block. Find a place within the block to split it.
801 // This is a little tricky on Thumb since instructions are 2 bytes
802 // and constant pool entries are 4 bytes: if instruction I references
803 // island CPE, and instruction I+1 references CPE', it will
804 // not work well to put CPE as far forward as possible, since then
805 // CPE' cannot immediately follow it (that location is 2 bytes
806 // farther away from I+1 than CPE was from I) and we'd need to create
809 // Solution of last resort: split the user's MBB right after the user
810 // and insert a clone of the CPE into the newly created water.
811 MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
812 NewMBB = SplitBlockBeforeInstr(NextMI);
816 // Okay, we know we can put an island before NewMBB now, do it!
817 MachineBasicBlock *NewIsland = new MachineBasicBlock();
818 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
820 // Update internal data structures to account for the newly inserted MBB.
821 UpdateForInsertedWaterBlock(NewIsland);
823 // Decrement the old entry, and remove it if refcount becomes 0.
824 DecrementOldEntry(CPI, CPEMI, Size);
826 // Now that we have an island to add the CPE to, clone the original CPE and
827 // add it to the island.
828 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
829 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
830 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
833 // Compensate for .align 2 in thumb mode.
834 if (isThumb) Size += 2;
835 // Increase the size of the island block to account for the new entry.
836 BBSizes[NewIsland->getNumber()] += Size;
837 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
838 AdjustBBOffsetsAfter(NewIsland, Size);
840 // Finally, change the CPI in the instruction operand to be ID.
841 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
842 if (UserMI->getOperand(i).isConstantPoolIndex()) {
843 UserMI->getOperand(i).setConstantPoolIndex(ID);
847 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
852 /// BBIsInRange - Returns true if the distance between specific MI and
853 /// specific BB can fit in MI's displacement field.
854 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
856 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
857 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
858 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
860 DOUT << "Branch of destination BB#" << DestBB->getNumber()
861 << " from BB#" << MI->getParent()->getNumber()
862 << " max delta=" << MaxDisp
863 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
865 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
868 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
869 /// away to fit in its displacement field.
870 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
871 MachineInstr *MI = Br.MI;
872 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
874 // Check to see if the DestBB is already in-range.
875 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
879 return FixUpUnconditionalBr(Fn, Br);
880 return FixUpConditionalBr(Fn, Br);
883 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
884 /// too far away to fit in its displacement field. If the LR register has been
885 /// spilled in the epilogue, then we can use BL to implement a far jump.
886 /// Otherwise, add an intermediate branch instruction to to a branch.
888 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
889 MachineInstr *MI = Br.MI;
890 MachineBasicBlock *MBB = MI->getParent();
891 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
893 // Use BL to implement far jump.
894 Br.MaxDisp = (1 << 21) * 2;
895 MI->setInstrDescriptor(TII->get(ARM::tBfar));
896 BBSizes[MBB->getNumber()] += 2;
897 AdjustBBOffsetsAfter(MBB, 2);
901 DOUT << " Changed B to long jump " << *MI;
906 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
907 /// the specific unconditional branch instruction.
908 static inline unsigned getUnconditionalBrDisp(int Opc) {
909 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
912 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
913 /// far away to fit in its displacement field. It is converted to an inverse
914 /// conditional branch + an unconditional branch to the destination.
916 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
917 MachineInstr *MI = Br.MI;
918 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
920 // Add a unconditional branch to the destination and invert the branch
921 // condition to jump over it:
927 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
928 CC = ARMCC::getOppositeCondition(CC);
930 // If the branch is at the end of its MBB and that has a fall-through block,
931 // direct the updated conditional branch to the fall-through block. Otherwise,
932 // split the MBB before the next instruction.
933 MachineBasicBlock *MBB = MI->getParent();
934 MachineInstr *BMI = &MBB->back();
935 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
939 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
940 BMI->getOpcode() == Br.UncondBr) {
941 // Last MI in the BB is a unconditional branch. Can we simply invert the
942 // condition and swap destinations:
948 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
949 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
950 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
951 BMI->getOperand(0).setMachineBasicBlock(DestBB);
952 MI->getOperand(0).setMachineBasicBlock(NewDest);
953 MI->getOperand(1).setImm(CC);
960 SplitBlockBeforeInstr(MI);
961 // No need for the branch to the next block. We're adding a unconditional
962 // branch to the destination.
963 MBB->back().eraseFromParent();
965 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
967 DOUT << " Insert B to BB#" << DestBB->getNumber()
968 << " also invert condition and change dest. to BB#"
969 << NextBB->getNumber() << "\n";
971 // Insert a unconditional branch and replace the conditional branch.
972 // Also update the ImmBranch as well as adding a new entry for the new branch.
973 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
974 Br.MI = &MBB->back();
975 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
976 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
977 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
978 MI->eraseFromParent();
980 // Increase the size of MBB to account for the new unconditional branch.
981 int delta = ARM::GetInstSize(&MBB->back());
982 BBSizes[MBB->getNumber()] += delta;
983 AdjustBBOffsetsAfter(MBB, delta);
987 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
988 /// LR / restores LR to pc.
989 bool ARMConstantIslands::UndoLRSpillRestore() {
990 bool MadeChange = false;
991 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
992 MachineInstr *MI = PushPopMIs[i];
993 if (MI->getNumOperands() == 1) {
994 if (MI->getOpcode() == ARM::tPOP_RET &&
995 MI->getOperand(0).getReg() == ARM::PC)
996 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
997 MI->eraseFromParent();