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 "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(NumCPEs, "Number of constpool entries");
33 STATISTIC(NumSplit, "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
38 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
41 /// constant pool; instead, it places constants wherever it feels like with
42 /// special instructions.
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51 /// by MBB Number. The two-byte pads required for Thumb alignment are
52 /// counted as part of the following block (i.e., the offset and size for
53 /// a padded block will both be ==2 mod 4).
54 std::vector<unsigned> BBSizes;
56 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
57 /// The two-byte pads required for Thumb alignment are counted as part of
58 /// the following block.
59 std::vector<unsigned> BBOffsets;
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 /// ImmBranches - 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 ARMFunctionInfo *AFI;
131 ARMConstantIslands() : MachineFunctionPass(&ID) {}
133 virtual bool runOnMachineFunction(MachineFunction &Fn);
135 virtual const char *getPassName() const {
136 return "ARM constant island placement and branch shortening pass";
140 void DoInitialPlacement(MachineFunction &Fn,
141 std::vector<MachineInstr*> &CPEMIs);
142 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
143 void InitialFunctionScan(MachineFunction &Fn,
144 const std::vector<MachineInstr*> &CPEMIs);
145 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
146 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
147 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
148 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
149 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
150 bool LookForWater(CPUser&U, unsigned UserOffset,
151 MachineBasicBlock** NewMBB);
152 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
153 std::vector<MachineBasicBlock*>::iterator IP);
154 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
155 MachineBasicBlock** NewMBB);
156 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
157 void RemoveDeadCPEMI(MachineInstr *CPEMI);
158 bool RemoveUnusedCPEntries();
159 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
160 MachineInstr *CPEMI, unsigned Disp,
162 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
164 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
165 unsigned Disp, bool NegativeOK);
166 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
167 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
168 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
169 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
170 bool UndoLRSpillRestore();
172 unsigned GetOffsetOf(MachineInstr *MI) const;
174 void verify(MachineFunction &Fn);
176 char ARMConstantIslands::ID = 0;
179 /// verify - check BBOffsets, BBSizes, alignment of islands
180 void ARMConstantIslands::verify(MachineFunction &Fn) {
181 assert(BBOffsets.size() == BBSizes.size());
182 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
183 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
185 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
187 MachineBasicBlock *MBB = MBBI;
189 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
190 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
191 BBSizes[MBB->getNumber()]%4 == 0) ||
192 (BBOffsets[MBB->getNumber()]%4 != 0 &&
193 BBSizes[MBB->getNumber()]%4 != 0));
198 /// print block size and offset information - debugging
199 void ARMConstantIslands::dumpBBs() {
200 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
201 DOUT << "block " << J << " offset " << BBOffsets[J] <<
202 " size " << BBSizes[J] << "\n";
206 /// createARMConstantIslandPass - returns an instance of the constpool
208 FunctionPass *llvm::createARMConstantIslandPass() {
209 return new ARMConstantIslands();
212 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
213 MachineConstantPool &MCP = *Fn.getConstantPool();
215 TII = Fn.getTarget().getInstrInfo();
216 AFI = Fn.getInfo<ARMFunctionInfo>();
217 isThumb = AFI->isThumbFunction();
218 isThumb1Only = AFI->isThumb1OnlyFunction();
219 isThumb2 = AFI->isThumb2Function();
223 // Renumber all of the machine basic blocks in the function, guaranteeing that
224 // the numbers agree with the position of the block in the function.
227 /// Thumb functions containing constant pools get 2-byte alignment.
228 /// This is so we can keep exact track of where the alignment padding goes.
230 AFI->setAlign(isThumb ? 1U : 2U);
232 // Perform the initial placement of the constant pool entries. To start with,
233 // we put them all at the end of the function.
234 std::vector<MachineInstr*> CPEMIs;
235 if (!MCP.isEmpty()) {
236 DoInitialPlacement(Fn, CPEMIs);
241 /// The next UID to take is the first unused one.
242 AFI->initConstPoolEntryUId(CPEMIs.size());
244 // Do the initial scan of the function, building up information about the
245 // sizes of each block, the location of all the water, and finding all of the
246 // constant pool users.
247 InitialFunctionScan(Fn, CPEMIs);
250 /// Remove dead constant pool entries.
251 RemoveUnusedCPEntries();
253 // Iteratively place constant pool entries and fix up branches until there
255 bool MadeChange = false;
258 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
259 Change |= HandleConstantPoolUser(Fn, i);
261 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
262 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
269 // After a while, this might be made debug-only, but it is not expensive.
272 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
273 // Undo the spill / restore of LR if possible.
274 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
275 MadeChange |= UndoLRSpillRestore();
288 /// DoInitialPlacement - Perform the initial placement of the constant pool
289 /// entries. To start with, we put them all at the end of the function.
290 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
291 std::vector<MachineInstr*> &CPEMIs) {
292 // Create the basic block to hold the CPE's.
293 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
296 // Add all of the constants from the constant pool to the end block, use an
297 // identity mapping of CPI's to CPE's.
298 const std::vector<MachineConstantPoolEntry> &CPs =
299 Fn.getConstantPool()->getConstants();
301 const TargetData &TD = *Fn.getTarget().getTargetData();
302 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
303 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
304 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
305 // we would have to pad them out or something so that instructions stay
307 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
308 MachineInstr *CPEMI =
309 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
310 .addImm(i).addConstantPoolIndex(i).addImm(Size);
311 CPEMIs.push_back(CPEMI);
313 // Add a new CPEntry, but no corresponding CPUser yet.
314 std::vector<CPEntry> CPEs;
315 CPEs.push_back(CPEntry(CPEMI, i));
316 CPEntries.push_back(CPEs);
318 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
322 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
323 /// into the block immediately after it.
324 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
325 // Get the next machine basic block in the function.
326 MachineFunction::iterator MBBI = MBB;
327 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
330 MachineBasicBlock *NextBB = next(MBBI);
331 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
332 E = MBB->succ_end(); I != E; ++I)
339 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
340 /// look up the corresponding CPEntry.
341 ARMConstantIslands::CPEntry
342 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
343 const MachineInstr *CPEMI) {
344 std::vector<CPEntry> &CPEs = CPEntries[CPI];
345 // Number of entries per constpool index should be small, just do a
347 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
348 if (CPEs[i].CPEMI == CPEMI)
354 /// InitialFunctionScan - Do the initial scan of the function, building up
355 /// information about the sizes of each block, the location of all the water,
356 /// and finding all of the constant pool users.
357 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
358 const std::vector<MachineInstr*> &CPEMIs) {
360 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
362 MachineBasicBlock &MBB = *MBBI;
364 // If this block doesn't fall through into the next MBB, then this is
365 // 'water' that a constant pool island could be placed.
366 if (!BBHasFallthrough(&MBB))
367 WaterList.push_back(&MBB);
369 unsigned MBBSize = 0;
370 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
372 // Add instruction size to MBBSize.
373 MBBSize += TII->GetInstSizeInBytes(I);
375 int Opc = I->getOpcode();
376 if (I->getDesc().isBranch()) {
385 case ARM::t2BR_JTadd:
386 // A Thumb table jump may involve padding; for the offsets to
387 // be right, functions containing these must be 4-byte aligned.
389 if ((Offset+MBBSize)%4 != 0)
390 MBBSize += 2; // padding
391 continue; // Does not get an entry in ImmBranches
393 continue; // Ignore other JT branches
424 // Record this immediate branch.
425 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
426 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
429 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
430 PushPopMIs.push_back(I);
432 // Scan the instructions for constant pool operands.
433 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
434 if (I->getOperand(op).isCPI()) {
435 // We found one. The addressing mode tells us the max displacement
436 // from the PC that this instruction permits.
438 // Basic size info comes from the TSFlags field.
441 unsigned TSFlags = I->getDesc().TSFlags;
442 switch (TSFlags & ARMII::AddrModeMask) {
444 // Constant pool entries can reach anything.
445 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
447 if (I->getOpcode() == ARM::tLEApcrel) {
448 Bits = 8; // Taking the address of a CP entry.
451 assert(0 && "Unknown addressing mode for CP reference!");
452 case ARMII::AddrMode1: // AM1: 8 bits << 2
454 Scale = 4; // Taking the address of a CP entry.
456 case ARMII::AddrMode2:
457 Bits = 12; // +-offset_12
459 case ARMII::AddrMode3:
460 Bits = 8; // +-offset_8
462 // addrmode4 has no immediate offset.
463 case ARMII::AddrMode5:
465 Scale = 4; // +-(offset_8*4)
467 // addrmode6 has no immediate offset.
468 case ARMII::AddrModeT1_1:
469 Bits = 5; // +offset_5
471 case ARMII::AddrModeT1_2:
473 Scale = 2; // +(offset_5*2)
475 case ARMII::AddrModeT1_4:
477 Scale = 4; // +(offset_5*4)
479 case ARMII::AddrModeT1_s:
481 Scale = 4; // +(offset_8*4)
483 case ARMII::AddrModeT2_pc:
484 Bits = 12; // +-offset_12
488 // Remember that this is a user of a CP entry.
489 unsigned CPI = I->getOperand(op).getIndex();
490 MachineInstr *CPEMI = CPEMIs[CPI];
491 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
492 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
494 // Increment corresponding CPEntry reference count.
495 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
496 assert(CPE && "Cannot find a corresponding CPEntry!");
499 // Instructions can only use one CP entry, don't bother scanning the
500 // rest of the operands.
505 // In thumb mode, if this block is a constpool island, we may need padding
506 // so it's aligned on 4 byte boundary.
509 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
513 BBSizes.push_back(MBBSize);
514 BBOffsets.push_back(Offset);
519 /// GetOffsetOf - Return the current offset of the specified machine instruction
520 /// from the start of the function. This offset changes as stuff is moved
521 /// around inside the function.
522 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
523 MachineBasicBlock *MBB = MI->getParent();
525 // The offset is composed of two things: the sum of the sizes of all MBB's
526 // before this instruction's block, and the offset from the start of the block
528 unsigned Offset = BBOffsets[MBB->getNumber()];
530 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
531 // alignment padding, and compensate if so.
533 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
537 // Sum instructions before MI in MBB.
538 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
539 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
540 if (&*I == MI) return Offset;
541 Offset += TII->GetInstSizeInBytes(I);
545 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
547 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
548 const MachineBasicBlock *RHS) {
549 return LHS->getNumber() < RHS->getNumber();
552 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
553 /// machine function, it upsets all of the block numbers. Renumber the blocks
554 /// and update the arrays that parallel this numbering.
555 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
556 // Renumber the MBB's to keep them consequtive.
557 NewBB->getParent()->RenumberBlocks(NewBB);
559 // Insert a size into BBSizes to align it properly with the (newly
560 // renumbered) block numbers.
561 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
563 // Likewise for BBOffsets.
564 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
566 // Next, update WaterList. Specifically, we need to add NewMBB as having
567 // available water after it.
568 std::vector<MachineBasicBlock*>::iterator IP =
569 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
571 WaterList.insert(IP, NewBB);
575 /// Split the basic block containing MI into two blocks, which are joined by
576 /// an unconditional branch. Update datastructures and renumber blocks to
577 /// account for this change and returns the newly created block.
578 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
579 MachineBasicBlock *OrigBB = MI->getParent();
580 MachineFunction &MF = *OrigBB->getParent();
582 // Create a new MBB for the code after the OrigBB.
583 MachineBasicBlock *NewBB =
584 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
585 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
586 MF.insert(MBBI, NewBB);
588 // Splice the instructions starting with MI over to NewBB.
589 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
591 // Add an unconditional branch from OrigBB to NewBB.
592 // Note the new unconditional branch is not being recorded.
593 // There doesn't seem to be meaningful DebugInfo available; this doesn't
594 // correspond to anything in the source.
595 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
596 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
599 // Update the CFG. All succs of OrigBB are now succs of NewBB.
600 while (!OrigBB->succ_empty()) {
601 MachineBasicBlock *Succ = *OrigBB->succ_begin();
602 OrigBB->removeSuccessor(Succ);
603 NewBB->addSuccessor(Succ);
605 // This pass should be run after register allocation, so there should be no
606 // PHI nodes to update.
607 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
608 && "PHI nodes should be eliminated by now!");
611 // OrigBB branches to NewBB.
612 OrigBB->addSuccessor(NewBB);
614 // Update internal data structures to account for the newly inserted MBB.
615 // This is almost the same as UpdateForInsertedWaterBlock, except that
616 // the Water goes after OrigBB, not NewBB.
617 MF.RenumberBlocks(NewBB);
619 // Insert a size into BBSizes to align it properly with the (newly
620 // renumbered) block numbers.
621 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
623 // Likewise for BBOffsets.
624 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
626 // Next, update WaterList. Specifically, we need to add OrigMBB as having
627 // available water after it (but not if it's already there, which happens
628 // when splitting before a conditional branch that is followed by an
629 // unconditional branch - in that case we want to insert NewBB).
630 std::vector<MachineBasicBlock*>::iterator IP =
631 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
633 MachineBasicBlock* WaterBB = *IP;
634 if (WaterBB == OrigBB)
635 WaterList.insert(next(IP), NewBB);
637 WaterList.insert(IP, OrigBB);
639 // Figure out how large the first NewMBB is. (It cannot
640 // contain a constpool_entry or tablejump.)
641 unsigned NewBBSize = 0;
642 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
644 NewBBSize += TII->GetInstSizeInBytes(I);
646 unsigned OrigBBI = OrigBB->getNumber();
647 unsigned NewBBI = NewBB->getNumber();
648 // Set the size of NewBB in BBSizes.
649 BBSizes[NewBBI] = NewBBSize;
651 // We removed instructions from UserMBB, subtract that off from its size.
652 // Add 2 or 4 to the block to count the unconditional branch we added to it.
653 unsigned delta = isThumb ? 2 : 4;
654 BBSizes[OrigBBI] -= NewBBSize - delta;
656 // ...and adjust BBOffsets for NewBB accordingly.
657 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
659 // All BBOffsets following these blocks must be modified.
660 AdjustBBOffsetsAfter(NewBB, delta);
665 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
666 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
667 /// constant pool entry).
668 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
669 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
670 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
671 // purposes of the displacement computation; compensate for that here.
672 // Effectively, the valid range of displacements is 2 bytes smaller for such
674 if (isThumb && UserOffset%4 !=0)
676 // CPEs will be rounded up to a multiple of 4.
677 if (isThumb && TrialOffset%4 != 0)
680 if (UserOffset <= TrialOffset) {
681 // User before the Trial.
682 if (TrialOffset-UserOffset <= MaxDisp)
684 } else if (NegativeOK) {
685 if (UserOffset-TrialOffset <= MaxDisp)
691 /// WaterIsInRange - Returns true if a CPE placed after the specified
692 /// Water (a basic block) will be in range for the specific MI.
694 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
695 MachineBasicBlock* Water, CPUser &U)
697 unsigned MaxDisp = U.MaxDisp;
698 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
699 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
700 BBSizes[Water->getNumber()];
702 // If the CPE is to be inserted before the instruction, that will raise
703 // the offset of the instruction. (Currently applies only to ARM, so
704 // no alignment compensation attempted here.)
705 if (CPEOffset < UserOffset)
706 UserOffset += U.CPEMI->getOperand(2).getImm();
708 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
711 /// CPEIsInRange - Returns true if the distance between specific MI and
712 /// specific ConstPool entry instruction can fit in MI's displacement field.
713 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
715 unsigned MaxDisp, bool DoDump) {
716 unsigned CPEOffset = GetOffsetOf(CPEMI);
717 assert(CPEOffset%4 == 0 && "Misaligned CPE");
720 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
721 << " max delta=" << MaxDisp
722 << " insn address=" << UserOffset
723 << " CPE address=" << CPEOffset
724 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
727 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
731 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
732 /// unconditionally branches to its only successor.
733 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
734 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
737 MachineBasicBlock *Succ = *MBB->succ_begin();
738 MachineBasicBlock *Pred = *MBB->pred_begin();
739 MachineInstr *PredMI = &Pred->back();
740 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
741 || PredMI->getOpcode() == ARM::t2B)
742 return PredMI->getOperand(0).getMBB() == Succ;
747 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
749 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
750 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
751 BBOffsets[i] += delta;
752 // If some existing blocks have padding, adjust the padding as needed, a
753 // bit tricky. delta can be negative so don't use % on that.
755 MachineBasicBlock *MBB = MBBI;
757 // Constant pool entries require padding.
758 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
759 unsigned oldOffset = BBOffsets[i] - delta;
760 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
764 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
765 // remove existing padding
770 // Thumb jump tables require padding. They should be at the end;
771 // following unconditional branches are removed by AnalyzeBranch.
772 MachineInstr *ThumbJTMI = NULL;
773 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
774 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
775 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
776 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
777 ThumbJTMI = prior(MBB->end());
779 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
780 unsigned oldMIOffset = newMIOffset - delta;
781 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
782 // remove existing padding
785 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
799 /// DecrementOldEntry - find the constant pool entry with index CPI
800 /// and instruction CPEMI, and decrement its refcount. If the refcount
801 /// becomes 0 remove the entry and instruction. Returns true if we removed
802 /// the entry, false if we didn't.
804 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
805 // Find the old entry. Eliminate it if it is no longer used.
806 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
807 assert(CPE && "Unexpected!");
808 if (--CPE->RefCount == 0) {
809 RemoveDeadCPEMI(CPEMI);
817 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
818 /// if not, see if an in-range clone of the CPE is in range, and if so,
819 /// change the data structures so the user references the clone. Returns:
820 /// 0 = no existing entry found
821 /// 1 = entry found, and there were no code insertions or deletions
822 /// 2 = entry found, and there were code insertions or deletions
823 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
825 MachineInstr *UserMI = U.MI;
826 MachineInstr *CPEMI = U.CPEMI;
828 // Check to see if the CPE is already in-range.
829 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
830 DOUT << "In range\n";
834 // No. Look for previously created clones of the CPE that are in range.
835 unsigned CPI = CPEMI->getOperand(1).getIndex();
836 std::vector<CPEntry> &CPEs = CPEntries[CPI];
837 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
838 // We already tried this one
839 if (CPEs[i].CPEMI == CPEMI)
841 // Removing CPEs can leave empty entries, skip
842 if (CPEs[i].CPEMI == NULL)
844 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
845 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
846 // Point the CPUser node to the replacement
847 U.CPEMI = CPEs[i].CPEMI;
848 // Change the CPI in the instruction operand to refer to the clone.
849 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
850 if (UserMI->getOperand(j).isCPI()) {
851 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
854 // Adjust the refcount of the clone...
856 // ...and the original. If we didn't remove the old entry, none of the
857 // addresses changed, so we don't need another pass.
858 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
864 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
865 /// the specific unconditional branch instruction.
866 static inline unsigned getUnconditionalBrDisp(int Opc) {
869 return ((1<<10)-1)*2;
871 return ((1<<23)-1)*2;
876 return ((1<<23)-1)*4;
879 /// AcceptWater - Small amount of common code factored out of the following.
881 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
882 std::vector<MachineBasicBlock*>::iterator IP) {
883 DOUT << "found water in range\n";
884 // Remove the original WaterList entry; we want subsequent
885 // insertions in this vicinity to go after the one we're
886 // about to insert. This considerably reduces the number
887 // of times we have to move the same CPE more than once.
889 // CPE goes before following block (NewMBB).
890 return next(MachineFunction::iterator(WaterBB));
893 /// LookForWater - look for an existing entry in the WaterList in which
894 /// we can place the CPE referenced from U so it's within range of U's MI.
895 /// Returns true if found, false if not. If it returns true, *NewMBB
896 /// is set to the WaterList entry.
897 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
898 /// water that will not introduce padding to water that will; within each
899 /// group, prefer the water that's farthest away.
901 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
902 MachineBasicBlock** NewMBB) {
903 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
904 MachineBasicBlock* WaterBBThatWouldPad = NULL;
905 if (!WaterList.empty()) {
906 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
907 B = WaterList.begin();; --IP) {
908 MachineBasicBlock* WaterBB = *IP;
909 if (WaterIsInRange(UserOffset, WaterBB, U)) {
911 (BBOffsets[WaterBB->getNumber()] +
912 BBSizes[WaterBB->getNumber()])%4 != 0) {
913 // This is valid Water, but would introduce padding. Remember
914 // it in case we don't find any Water that doesn't do this.
915 if (!WaterBBThatWouldPad) {
916 WaterBBThatWouldPad = WaterBB;
920 *NewMBB = AcceptWater(WaterBB, IP);
928 if (isThumb && WaterBBThatWouldPad) {
929 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
935 /// CreateNewWater - No existing WaterList entry will work for
936 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
937 /// block is used if in range, and the conditional branch munged so control
938 /// flow is correct. Otherwise the block is split to create a hole with an
939 /// unconditional branch around it. In either case *NewMBB is set to a
940 /// block following which the new island can be inserted (the WaterList
941 /// is not adjusted).
943 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
944 unsigned UserOffset, MachineBasicBlock** NewMBB) {
945 CPUser &U = CPUsers[CPUserIndex];
946 MachineInstr *UserMI = U.MI;
947 MachineInstr *CPEMI = U.CPEMI;
948 MachineBasicBlock *UserMBB = UserMI->getParent();
949 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
950 BBSizes[UserMBB->getNumber()];
951 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
953 // If the use is at the end of the block, or the end of the block
954 // is within range, make new water there. (The addition below is
955 // for the unconditional branch we will be adding: 4 bytes on ARM,
956 // 2 on Thumb. Possible Thumb alignment padding is allowed for
957 // inside OffsetIsInRange.
958 // If the block ends in an unconditional branch already, it is water,
959 // and is known to be out of range, so we'll always be adding a branch.)
960 if (&UserMBB->back() == UserMI ||
961 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
962 U.MaxDisp, !isThumb)) {
963 DOUT << "Split at end of block\n";
964 if (&UserMBB->back() == UserMI)
965 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
966 *NewMBB = next(MachineFunction::iterator(UserMBB));
967 // Add an unconditional branch from UserMBB to fallthrough block.
968 // Record it for branch lengthening; this new branch will not get out of
969 // range, but if the preceding conditional branch is out of range, the
970 // targets will be exchanged, and the altered branch may be out of
971 // range, so the machinery has to know about it.
972 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
973 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
974 TII->get(UncondBr)).addMBB(*NewMBB);
975 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
976 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
977 MaxDisp, false, UncondBr));
978 int delta = isThumb ? 2 : 4;
979 BBSizes[UserMBB->getNumber()] += delta;
980 AdjustBBOffsetsAfter(UserMBB, delta);
982 // What a big block. Find a place within the block to split it.
983 // This is a little tricky on Thumb since instructions are 2 bytes
984 // and constant pool entries are 4 bytes: if instruction I references
985 // island CPE, and instruction I+1 references CPE', it will
986 // not work well to put CPE as far forward as possible, since then
987 // CPE' cannot immediately follow it (that location is 2 bytes
988 // farther away from I+1 than CPE was from I) and we'd need to create
989 // a new island. So, we make a first guess, then walk through the
990 // instructions between the one currently being looked at and the
991 // possible insertion point, and make sure any other instructions
992 // that reference CPEs will be able to use the same island area;
993 // if not, we back up the insertion point.
995 // The 4 in the following is for the unconditional branch we'll be
996 // inserting (allows for long branch on Thumb). Alignment of the
997 // island is handled inside OffsetIsInRange.
998 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
999 // This could point off the end of the block if we've already got
1000 // constant pool entries following this block; only the last one is
1001 // in the water list. Back past any possible branches (allow for a
1002 // conditional and a maximally long unconditional).
1003 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1004 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1006 unsigned EndInsertOffset = BaseInsertOffset +
1007 CPEMI->getOperand(2).getImm();
1008 MachineBasicBlock::iterator MI = UserMI;
1010 unsigned CPUIndex = CPUserIndex+1;
1011 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1012 Offset < BaseInsertOffset;
1013 Offset += TII->GetInstSizeInBytes(MI),
1015 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1016 if (!OffsetIsInRange(Offset, EndInsertOffset,
1017 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1018 BaseInsertOffset -= (isThumb ? 2 : 4);
1019 EndInsertOffset -= (isThumb ? 2 : 4);
1021 // This is overly conservative, as we don't account for CPEMIs
1022 // being reused within the block, but it doesn't matter much.
1023 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1027 DOUT << "Split in middle of big block\n";
1028 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1032 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1033 /// is out-of-range. If so, pick up the constant pool value and move it some
1034 /// place in-range. Return true if we changed any addresses (thus must run
1035 /// another pass of branch lengthening), false otherwise.
1036 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1037 unsigned CPUserIndex) {
1038 CPUser &U = CPUsers[CPUserIndex];
1039 MachineInstr *UserMI = U.MI;
1040 MachineInstr *CPEMI = U.CPEMI;
1041 unsigned CPI = CPEMI->getOperand(1).getIndex();
1042 unsigned Size = CPEMI->getOperand(2).getImm();
1043 MachineBasicBlock *NewMBB;
1044 // Compute this only once, it's expensive. The 4 or 8 is the value the
1045 // hardware keeps in the PC (2 insns ahead of the reference).
1046 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1048 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1049 // second instruction.
1050 if (UserMI->getOpcode() == ARM::tLEApcrel)
1053 // See if the current entry is within range, or there is a clone of it
1055 int result = LookForExistingCPEntry(U, UserOffset);
1056 if (result==1) return false;
1057 else if (result==2) return true;
1059 // No existing clone of this CPE is within range.
1060 // We will be generating a new clone. Get a UID for it.
1061 unsigned ID = AFI->createConstPoolEntryUId();
1063 // Look for water where we can place this CPE. We look for the farthest one
1064 // away that will work. Forward references only for now (although later
1065 // we might find some that are backwards).
1067 if (!LookForWater(U, UserOffset, &NewMBB)) {
1069 DOUT << "No water found\n";
1070 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1073 // Okay, we know we can put an island before NewMBB now, do it!
1074 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1075 Fn.insert(NewMBB, NewIsland);
1077 // Update internal data structures to account for the newly inserted MBB.
1078 UpdateForInsertedWaterBlock(NewIsland);
1080 // Decrement the old entry, and remove it if refcount becomes 0.
1081 DecrementOldEntry(CPI, CPEMI);
1083 // Now that we have an island to add the CPE to, clone the original CPE and
1084 // add it to the island.
1085 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1086 TII->get(ARM::CONSTPOOL_ENTRY))
1087 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1088 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1091 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1092 // Compensate for .align 2 in thumb mode.
1093 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1095 // Increase the size of the island block to account for the new entry.
1096 BBSizes[NewIsland->getNumber()] += Size;
1097 AdjustBBOffsetsAfter(NewIsland, Size);
1099 // Finally, change the CPI in the instruction operand to be ID.
1100 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1101 if (UserMI->getOperand(i).isCPI()) {
1102 UserMI->getOperand(i).setIndex(ID);
1106 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1111 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1112 /// sizes and offsets of impacted basic blocks.
1113 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1114 MachineBasicBlock *CPEBB = CPEMI->getParent();
1115 unsigned Size = CPEMI->getOperand(2).getImm();
1116 CPEMI->eraseFromParent();
1117 BBSizes[CPEBB->getNumber()] -= Size;
1118 // All succeeding offsets have the current size value added in, fix this.
1119 if (CPEBB->empty()) {
1120 // In thumb mode, the size of island may be padded by two to compensate for
1121 // the alignment requirement. Then it will now be 2 when the block is
1122 // empty, so fix this.
1123 // All succeeding offsets have the current size value added in, fix this.
1124 if (BBSizes[CPEBB->getNumber()] != 0) {
1125 Size += BBSizes[CPEBB->getNumber()];
1126 BBSizes[CPEBB->getNumber()] = 0;
1129 AdjustBBOffsetsAfter(CPEBB, -Size);
1130 // An island has only one predecessor BB and one successor BB. Check if
1131 // this BB's predecessor jumps directly to this BB's successor. This
1132 // shouldn't happen currently.
1133 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1134 // FIXME: remove the empty blocks after all the work is done?
1137 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1139 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1140 unsigned MadeChange = false;
1141 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1142 std::vector<CPEntry> &CPEs = CPEntries[i];
1143 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1144 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1145 RemoveDeadCPEMI(CPEs[j].CPEMI);
1146 CPEs[j].CPEMI = NULL;
1154 /// BBIsInRange - Returns true if the distance between specific MI and
1155 /// specific BB can fit in MI's displacement field.
1156 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1158 unsigned PCAdj = isThumb ? 4 : 8;
1159 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1160 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1162 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1163 << " from BB#" << MI->getParent()->getNumber()
1164 << " max delta=" << MaxDisp
1165 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1166 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1168 if (BrOffset <= DestOffset) {
1169 // Branch before the Dest.
1170 if (DestOffset-BrOffset <= MaxDisp)
1173 if (BrOffset-DestOffset <= MaxDisp)
1179 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1180 /// away to fit in its displacement field.
1181 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1182 MachineInstr *MI = Br.MI;
1183 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1185 // Check to see if the DestBB is already in-range.
1186 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1190 return FixUpUnconditionalBr(Fn, Br);
1191 return FixUpConditionalBr(Fn, Br);
1194 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1195 /// too far away to fit in its displacement field. If the LR register has been
1196 /// spilled in the epilogue, then we can use BL to implement a far jump.
1197 /// Otherwise, add an intermediate branch instruction to a branch.
1199 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1200 MachineInstr *MI = Br.MI;
1201 MachineBasicBlock *MBB = MI->getParent();
1202 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
1204 // Use BL to implement far jump.
1205 Br.MaxDisp = (1 << 21) * 2;
1206 MI->setDesc(TII->get(ARM::tBfar));
1207 BBSizes[MBB->getNumber()] += 2;
1208 AdjustBBOffsetsAfter(MBB, 2);
1212 DOUT << " Changed B to long jump " << *MI;
1217 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1218 /// far away to fit in its displacement field. It is converted to an inverse
1219 /// conditional branch + an unconditional branch to the destination.
1221 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1222 MachineInstr *MI = Br.MI;
1223 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1225 // Add an unconditional branch to the destination and invert the branch
1226 // condition to jump over it:
1232 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1233 CC = ARMCC::getOppositeCondition(CC);
1234 unsigned CCReg = MI->getOperand(2).getReg();
1236 // If the branch is at the end of its MBB and that has a fall-through block,
1237 // direct the updated conditional branch to the fall-through block. Otherwise,
1238 // split the MBB before the next instruction.
1239 MachineBasicBlock *MBB = MI->getParent();
1240 MachineInstr *BMI = &MBB->back();
1241 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1245 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1246 BMI->getOpcode() == Br.UncondBr) {
1247 // Last MI in the BB is an unconditional branch. Can we simply invert the
1248 // condition and swap destinations:
1254 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1255 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1256 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
1257 BMI->getOperand(0).setMBB(DestBB);
1258 MI->getOperand(0).setMBB(NewDest);
1259 MI->getOperand(1).setImm(CC);
1266 SplitBlockBeforeInstr(MI);
1267 // No need for the branch to the next block. We're adding an unconditional
1268 // branch to the destination.
1269 int delta = TII->GetInstSizeInBytes(&MBB->back());
1270 BBSizes[MBB->getNumber()] -= delta;
1271 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1272 AdjustBBOffsetsAfter(SplitBB, -delta);
1273 MBB->back().eraseFromParent();
1274 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1276 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1278 DOUT << " Insert B to BB#" << DestBB->getNumber()
1279 << " also invert condition and change dest. to BB#"
1280 << NextBB->getNumber() << "\n";
1282 // Insert a new conditional branch and a new unconditional branch.
1283 // Also update the ImmBranch as well as adding a new entry for the new branch.
1284 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1285 TII->get(MI->getOpcode()))
1286 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1287 Br.MI = &MBB->back();
1288 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1289 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1290 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1291 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1292 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1294 // Remove the old conditional branch. It may or may not still be in MBB.
1295 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1296 MI->eraseFromParent();
1298 // The net size change is an addition of one unconditional branch.
1299 int delta = TII->GetInstSizeInBytes(&MBB->back());
1300 AdjustBBOffsetsAfter(MBB, delta);
1304 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1305 /// LR / restores LR to pc.
1306 bool ARMConstantIslands::UndoLRSpillRestore() {
1307 bool MadeChange = false;
1308 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1309 MachineInstr *MI = PushPopMIs[i];
1310 if (MI->getOpcode() == ARM::tPOP_RET &&
1311 MI->getOperand(0).getReg() == ARM::PC &&
1312 MI->getNumExplicitOperands() == 1) {
1313 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1314 MI->eraseFromParent();