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/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/Statistic.h"
35 STATISTIC(NumCPEs, "Number of constpool entries");
36 STATISTIC(NumSplit, "Number of uncond branches inserted");
37 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
38 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39 STATISTIC(NumTBs, "Number of table branches generated");
42 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
43 /// requires constant pool entries to be scattered among the instructions
44 /// inside a function. To do this, it completely ignores the normal LLVM
45 /// constant pool; instead, it places constants wherever it feels like with
46 /// special instructions.
48 /// The terminology used in this pass includes:
49 /// Islands - Clumps of constants placed in the function.
50 /// Water - Potential places where an island could be formed.
51 /// CPE - A constant pool entry that has been placed somewhere, which
52 /// tracks a list of users.
53 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
54 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
55 /// by MBB Number. The two-byte pads required for Thumb alignment are
56 /// counted as part of the following block (i.e., the offset and size for
57 /// a padded block will both be ==2 mod 4).
58 std::vector<unsigned> BBSizes;
60 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
61 /// The two-byte pads required for Thumb alignment are counted as part of
62 /// the following block.
63 std::vector<unsigned> BBOffsets;
65 /// WaterList - A sorted list of basic blocks where islands could be placed
66 /// (i.e. blocks that don't fall through to the following block, due
67 /// to a return, unreachable, or unconditional branch).
68 std::vector<MachineBasicBlock*> WaterList;
70 /// CPUser - One user of a constant pool, keeping the machine instruction
71 /// pointer, the constant pool being referenced, and the max displacement
72 /// allowed from the instruction to the CP.
79 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
81 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
84 /// CPUsers - Keep track of all of the machine instructions that use various
85 /// constant pools and their max displacement.
86 std::vector<CPUser> CPUsers;
88 /// CPEntry - One per constant pool entry, keeping the machine instruction
89 /// pointer, the constpool index, and the number of CPUser's which
90 /// reference this entry.
95 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
96 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
99 /// CPEntries - Keep track of all of the constant pool entry machine
100 /// instructions. For each original constpool index (i.e. those that
101 /// existed upon entry to this pass), it keeps a vector of entries.
102 /// Original elements are cloned as we go along; the clones are
103 /// put in the vector of the original element, but have distinct CPIs.
104 std::vector<std::vector<CPEntry> > CPEntries;
106 /// ImmBranch - One per immediate branch, keeping the machine instruction
107 /// pointer, conditional or unconditional, the max displacement,
108 /// and (if isCond is true) the corresponding unconditional branch
112 unsigned MaxDisp : 31;
115 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
116 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
119 /// ImmBranches - Keep track of all the immediate branch instructions.
121 std::vector<ImmBranch> ImmBranches;
123 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
125 SmallVector<MachineInstr*, 4> PushPopMIs;
127 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
128 SmallVector<MachineInstr*, 4> T2JumpTables;
130 /// HasFarJump - True if any far jump instruction has been emitted during
131 /// the branch fix up pass.
134 const TargetInstrInfo *TII;
135 const ARMSubtarget *STI;
136 ARMFunctionInfo *AFI;
142 ARMConstantIslands() : MachineFunctionPass(&ID) {}
144 virtual bool runOnMachineFunction(MachineFunction &MF);
146 virtual const char *getPassName() const {
147 return "ARM constant island placement and branch shortening pass";
151 void DoInitialPlacement(MachineFunction &MF,
152 std::vector<MachineInstr*> &CPEMIs);
153 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
154 void InitialFunctionScan(MachineFunction &MF,
155 const std::vector<MachineInstr*> &CPEMIs);
156 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
157 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
158 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
159 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
160 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
161 bool LookForWater(CPUser&U, unsigned UserOffset,
162 MachineBasicBlock** NewMBB);
163 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
164 std::vector<MachineBasicBlock*>::iterator IP);
165 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
166 MachineBasicBlock** NewMBB);
167 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
168 void RemoveDeadCPEMI(MachineInstr *CPEMI);
169 bool RemoveUnusedCPEntries();
170 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
171 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
172 bool DoDump = false);
173 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
175 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
176 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
177 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
178 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
179 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
180 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
181 bool UndoLRSpillRestore();
182 bool OptimizeThumb2JumpTables(MachineFunction &MF);
184 unsigned GetOffsetOf(MachineInstr *MI) const;
186 void verify(MachineFunction &MF);
188 char ARMConstantIslands::ID = 0;
191 /// verify - check BBOffsets, BBSizes, alignment of islands
192 void ARMConstantIslands::verify(MachineFunction &MF) {
193 assert(BBOffsets.size() == BBSizes.size());
194 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
195 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
199 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
201 MachineBasicBlock *MBB = MBBI;
203 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
204 unsigned MBBId = MBB->getNumber();
205 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
206 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
212 /// print block size and offset information - debugging
213 void ARMConstantIslands::dumpBBs() {
214 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
215 DOUT << "block " << J << " offset " << BBOffsets[J] <<
216 " size " << BBSizes[J] << "\n";
220 /// createARMConstantIslandPass - returns an instance of the constpool
222 FunctionPass *llvm::createARMConstantIslandPass() {
223 return new ARMConstantIslands();
226 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
227 MachineConstantPool &MCP = *MF.getConstantPool();
229 TII = MF.getTarget().getInstrInfo();
230 AFI = MF.getInfo<ARMFunctionInfo>();
231 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
233 isThumb = AFI->isThumbFunction();
234 isThumb1 = AFI->isThumb1OnlyFunction();
235 isThumb2 = AFI->isThumb2Function();
239 // Renumber all of the machine basic blocks in the function, guaranteeing that
240 // the numbers agree with the position of the block in the function.
243 // Thumb1 functions containing constant pools get 4-byte alignment.
244 // This is so we can keep exact track of where the alignment padding goes.
246 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
248 AFI->setAlign(isThumb1 ? 1U : 2U);
250 // Perform the initial placement of the constant pool entries. To start with,
251 // we put them all at the end of the function.
252 std::vector<MachineInstr*> CPEMIs;
253 if (!MCP.isEmpty()) {
254 DoInitialPlacement(MF, CPEMIs);
259 /// The next UID to take is the first unused one.
260 AFI->initConstPoolEntryUId(CPEMIs.size());
262 // Do the initial scan of the function, building up information about the
263 // sizes of each block, the location of all the water, and finding all of the
264 // constant pool users.
265 InitialFunctionScan(MF, CPEMIs);
268 /// Remove dead constant pool entries.
269 RemoveUnusedCPEntries();
271 // Iteratively place constant pool entries and fix up branches until there
273 bool MadeChange = false;
276 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
277 Change |= HandleConstantPoolUser(MF, i);
279 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
280 Change |= FixUpImmediateBr(MF, ImmBranches[i]);
287 // Let's see if we can use tbb / tbh to do jump tables.
288 MadeChange |= OptimizeThumb2JumpTables(MF);
290 // After a while, this might be made debug-only, but it is not expensive.
293 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
294 // Undo the spill / restore of LR if possible.
295 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
296 MadeChange |= UndoLRSpillRestore();
305 T2JumpTables.clear();
310 /// DoInitialPlacement - Perform the initial placement of the constant pool
311 /// entries. To start with, we put them all at the end of the function.
312 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
313 std::vector<MachineInstr*> &CPEMIs) {
314 // Create the basic block to hold the CPE's.
315 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
318 // Add all of the constants from the constant pool to the end block, use an
319 // identity mapping of CPI's to CPE's.
320 const std::vector<MachineConstantPoolEntry> &CPs =
321 MF.getConstantPool()->getConstants();
323 const TargetData &TD = *MF.getTarget().getTargetData();
324 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
325 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
326 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
327 // we would have to pad them out or something so that instructions stay
329 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
330 MachineInstr *CPEMI =
331 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
332 .addImm(i).addConstantPoolIndex(i).addImm(Size);
333 CPEMIs.push_back(CPEMI);
335 // Add a new CPEntry, but no corresponding CPUser yet.
336 std::vector<CPEntry> CPEs;
337 CPEs.push_back(CPEntry(CPEMI, i));
338 CPEntries.push_back(CPEs);
340 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
344 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
345 /// into the block immediately after it.
346 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
347 // Get the next machine basic block in the function.
348 MachineFunction::iterator MBBI = MBB;
349 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
352 MachineBasicBlock *NextBB = next(MBBI);
353 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
354 E = MBB->succ_end(); I != E; ++I)
361 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
362 /// look up the corresponding CPEntry.
363 ARMConstantIslands::CPEntry
364 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
365 const MachineInstr *CPEMI) {
366 std::vector<CPEntry> &CPEs = CPEntries[CPI];
367 // Number of entries per constpool index should be small, just do a
369 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
370 if (CPEs[i].CPEMI == CPEMI)
376 /// InitialFunctionScan - Do the initial scan of the function, building up
377 /// information about the sizes of each block, the location of all the water,
378 /// and finding all of the constant pool users.
379 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
380 const std::vector<MachineInstr*> &CPEMIs) {
382 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
384 MachineBasicBlock &MBB = *MBBI;
386 // If this block doesn't fall through into the next MBB, then this is
387 // 'water' that a constant pool island could be placed.
388 if (!BBHasFallthrough(&MBB))
389 WaterList.push_back(&MBB);
391 unsigned MBBSize = 0;
392 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
394 // Add instruction size to MBBSize.
395 MBBSize += TII->GetInstSizeInBytes(I);
397 int Opc = I->getOpcode();
398 if (I->getDesc().isBranch()) {
405 continue; // Ignore other JT branches
407 // A Thumb1 table jump may involve padding; for the offsets to
408 // be right, functions containing these must be 4-byte aligned.
410 if ((Offset+MBBSize)%4 != 0)
411 // FIXME: Add a pseudo ALIGN instruction instead.
412 MBBSize += 2; // padding
413 continue; // Does not get an entry in ImmBranches
415 T2JumpTables.push_back(I);
416 continue; // Does not get an entry in ImmBranches
447 // Record this immediate branch.
448 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
449 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
452 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
453 PushPopMIs.push_back(I);
455 if (Opc == ARM::CONSTPOOL_ENTRY)
458 // Scan the instructions for constant pool operands.
459 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
460 if (I->getOperand(op).isCPI()) {
461 // We found one. The addressing mode tells us the max displacement
462 // from the PC that this instruction permits.
464 // Basic size info comes from the TSFlags field.
468 bool IsSoImm = false;
470 // FIXME: Temporary workaround until I can figure out what's going on.
471 unsigned Slack = T2JumpTables.empty() ? 0 : 4;
474 llvm_unreachable("Unknown addressing mode for CP reference!");
477 // Taking the address of a CP entry.
479 // This takes a SoImm, which is 8 bit immediate rotated. We'll
480 // pretend the maximum offset is 255 * 4. Since each instruction
481 // 4 byte wide, this is always correct. We'llc heck for other
482 // displacements that fits in a SoImm as well.
488 case ARM::t2LEApcrel:
500 Bits = 12; // +-offset_12
507 Scale = 4; // +(offset_8*4)
513 Scale = 4; // +-(offset_8*4)
518 // Remember that this is a user of a CP entry.
519 unsigned CPI = I->getOperand(op).getIndex();
520 MachineInstr *CPEMI = CPEMIs[CPI];
521 unsigned MaxOffs = ((1 << Bits)-1) * Scale - Slack;
522 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
524 // Increment corresponding CPEntry reference count.
525 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
526 assert(CPE && "Cannot find a corresponding CPEntry!");
529 // Instructions can only use one CP entry, don't bother scanning the
530 // rest of the operands.
535 // In thumb mode, if this block is a constpool island, we may need padding
536 // so it's aligned on 4 byte boundary.
539 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
543 BBSizes.push_back(MBBSize);
544 BBOffsets.push_back(Offset);
549 /// GetOffsetOf - Return the current offset of the specified machine instruction
550 /// from the start of the function. This offset changes as stuff is moved
551 /// around inside the function.
552 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
553 MachineBasicBlock *MBB = MI->getParent();
555 // The offset is composed of two things: the sum of the sizes of all MBB's
556 // before this instruction's block, and the offset from the start of the block
558 unsigned Offset = BBOffsets[MBB->getNumber()];
560 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
561 // alignment padding, and compensate if so.
563 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
567 // Sum instructions before MI in MBB.
568 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
569 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
570 if (&*I == MI) return Offset;
571 Offset += TII->GetInstSizeInBytes(I);
575 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
577 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
578 const MachineBasicBlock *RHS) {
579 return LHS->getNumber() < RHS->getNumber();
582 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
583 /// machine function, it upsets all of the block numbers. Renumber the blocks
584 /// and update the arrays that parallel this numbering.
585 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
586 // Renumber the MBB's to keep them consequtive.
587 NewBB->getParent()->RenumberBlocks(NewBB);
589 // Insert a size into BBSizes to align it properly with the (newly
590 // renumbered) block numbers.
591 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
593 // Likewise for BBOffsets.
594 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
596 // Next, update WaterList. Specifically, we need to add NewMBB as having
597 // available water after it.
598 std::vector<MachineBasicBlock*>::iterator IP =
599 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
601 WaterList.insert(IP, NewBB);
605 /// Split the basic block containing MI into two blocks, which are joined by
606 /// an unconditional branch. Update datastructures and renumber blocks to
607 /// account for this change and returns the newly created block.
608 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
609 MachineBasicBlock *OrigBB = MI->getParent();
610 MachineFunction &MF = *OrigBB->getParent();
612 // Create a new MBB for the code after the OrigBB.
613 MachineBasicBlock *NewBB =
614 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
615 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
616 MF.insert(MBBI, NewBB);
618 // Splice the instructions starting with MI over to NewBB.
619 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
621 // Add an unconditional branch from OrigBB to NewBB.
622 // Note the new unconditional branch is not being recorded.
623 // There doesn't seem to be meaningful DebugInfo available; this doesn't
624 // correspond to anything in the source.
625 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
626 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
629 // Update the CFG. All succs of OrigBB are now succs of NewBB.
630 while (!OrigBB->succ_empty()) {
631 MachineBasicBlock *Succ = *OrigBB->succ_begin();
632 OrigBB->removeSuccessor(Succ);
633 NewBB->addSuccessor(Succ);
635 // This pass should be run after register allocation, so there should be no
636 // PHI nodes to update.
637 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
638 && "PHI nodes should be eliminated by now!");
641 // OrigBB branches to NewBB.
642 OrigBB->addSuccessor(NewBB);
644 // Update internal data structures to account for the newly inserted MBB.
645 // This is almost the same as UpdateForInsertedWaterBlock, except that
646 // the Water goes after OrigBB, not NewBB.
647 MF.RenumberBlocks(NewBB);
649 // Insert a size into BBSizes to align it properly with the (newly
650 // renumbered) block numbers.
651 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
653 // Likewise for BBOffsets.
654 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
656 // Next, update WaterList. Specifically, we need to add OrigMBB as having
657 // available water after it (but not if it's already there, which happens
658 // when splitting before a conditional branch that is followed by an
659 // unconditional branch - in that case we want to insert NewBB).
660 std::vector<MachineBasicBlock*>::iterator IP =
661 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
663 MachineBasicBlock* WaterBB = *IP;
664 if (WaterBB == OrigBB)
665 WaterList.insert(next(IP), NewBB);
667 WaterList.insert(IP, OrigBB);
669 // Figure out how large the first NewMBB is. (It cannot
670 // contain a constpool_entry or tablejump.)
671 unsigned NewBBSize = 0;
672 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
674 NewBBSize += TII->GetInstSizeInBytes(I);
676 unsigned OrigBBI = OrigBB->getNumber();
677 unsigned NewBBI = NewBB->getNumber();
678 // Set the size of NewBB in BBSizes.
679 BBSizes[NewBBI] = NewBBSize;
681 // We removed instructions from UserMBB, subtract that off from its size.
682 // Add 2 or 4 to the block to count the unconditional branch we added to it.
683 int delta = isThumb1 ? 2 : 4;
684 BBSizes[OrigBBI] -= NewBBSize - delta;
686 // ...and adjust BBOffsets for NewBB accordingly.
687 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
689 // All BBOffsets following these blocks must be modified.
690 AdjustBBOffsetsAfter(NewBB, delta);
695 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
696 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
697 /// constant pool entry).
698 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
699 unsigned TrialOffset, unsigned MaxDisp,
700 bool NegativeOK, bool IsSoImm) {
701 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
702 // purposes of the displacement computation; compensate for that here.
703 // Effectively, the valid range of displacements is 2 bytes smaller for such
705 if (isThumb && UserOffset%4 !=0)
707 // CPEs will be rounded up to a multiple of 4.
708 if (isThumb && TrialOffset%4 != 0)
711 if (UserOffset <= TrialOffset) {
712 // User before the Trial.
713 if (TrialOffset - UserOffset <= MaxDisp)
715 // FIXME: Make use full range of soimm values.
716 } else if (NegativeOK) {
717 if (UserOffset - TrialOffset <= MaxDisp)
719 // FIXME: Make use full range of soimm values.
724 /// WaterIsInRange - Returns true if a CPE placed after the specified
725 /// Water (a basic block) will be in range for the specific MI.
727 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
728 MachineBasicBlock* Water, CPUser &U) {
729 unsigned MaxDisp = U.MaxDisp;
730 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
731 BBSizes[Water->getNumber()];
733 // If the CPE is to be inserted before the instruction, that will raise
734 // the offset of the instruction. (Currently applies only to ARM, so
735 // no alignment compensation attempted here.)
736 if (CPEOffset < UserOffset)
737 UserOffset += U.CPEMI->getOperand(2).getImm();
739 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
742 /// CPEIsInRange - Returns true if the distance between specific MI and
743 /// specific ConstPool entry instruction can fit in MI's displacement field.
744 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
745 MachineInstr *CPEMI, unsigned MaxDisp,
746 bool NegOk, bool DoDump) {
747 unsigned CPEOffset = GetOffsetOf(CPEMI);
748 assert(CPEOffset%4 == 0 && "Misaligned CPE");
751 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
752 << " max delta=" << MaxDisp
753 << " insn address=" << UserOffset
754 << " CPE address=" << CPEOffset
755 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
758 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
762 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
763 /// unconditionally branches to its only successor.
764 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
765 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
768 MachineBasicBlock *Succ = *MBB->succ_begin();
769 MachineBasicBlock *Pred = *MBB->pred_begin();
770 MachineInstr *PredMI = &Pred->back();
771 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
772 || PredMI->getOpcode() == ARM::t2B)
773 return PredMI->getOperand(0).getMBB() == Succ;
778 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
780 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
781 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
783 BBOffsets[i] += delta;
784 // If some existing blocks have padding, adjust the padding as needed, a
785 // bit tricky. delta can be negative so don't use % on that.
788 MachineBasicBlock *MBB = MBBI;
790 // Constant pool entries require padding.
791 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
792 unsigned oldOffset = BBOffsets[i] - delta;
793 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
797 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
798 // remove existing padding
803 // Thumb1 jump tables require padding. They should be at the end;
804 // following unconditional branches are removed by AnalyzeBranch.
805 MachineInstr *ThumbJTMI = prior(MBB->end());
806 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
807 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
808 unsigned oldMIOffset = newMIOffset - delta;
809 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
810 // remove existing padding
813 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
826 /// DecrementOldEntry - find the constant pool entry with index CPI
827 /// and instruction CPEMI, and decrement its refcount. If the refcount
828 /// becomes 0 remove the entry and instruction. Returns true if we removed
829 /// the entry, false if we didn't.
831 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
832 // Find the old entry. Eliminate it if it is no longer used.
833 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
834 assert(CPE && "Unexpected!");
835 if (--CPE->RefCount == 0) {
836 RemoveDeadCPEMI(CPEMI);
844 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
845 /// if not, see if an in-range clone of the CPE is in range, and if so,
846 /// change the data structures so the user references the clone. Returns:
847 /// 0 = no existing entry found
848 /// 1 = entry found, and there were no code insertions or deletions
849 /// 2 = entry found, and there were code insertions or deletions
850 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
852 MachineInstr *UserMI = U.MI;
853 MachineInstr *CPEMI = U.CPEMI;
855 // Check to see if the CPE is already in-range.
856 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
857 DOUT << "In range\n";
861 // No. Look for previously created clones of the CPE that are in range.
862 unsigned CPI = CPEMI->getOperand(1).getIndex();
863 std::vector<CPEntry> &CPEs = CPEntries[CPI];
864 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
865 // We already tried this one
866 if (CPEs[i].CPEMI == CPEMI)
868 // Removing CPEs can leave empty entries, skip
869 if (CPEs[i].CPEMI == NULL)
871 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
872 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
873 // Point the CPUser node to the replacement
874 U.CPEMI = CPEs[i].CPEMI;
875 // Change the CPI in the instruction operand to refer to the clone.
876 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
877 if (UserMI->getOperand(j).isCPI()) {
878 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
881 // Adjust the refcount of the clone...
883 // ...and the original. If we didn't remove the old entry, none of the
884 // addresses changed, so we don't need another pass.
885 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
891 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
892 /// the specific unconditional branch instruction.
893 static inline unsigned getUnconditionalBrDisp(int Opc) {
896 return ((1<<10)-1)*2;
898 return ((1<<23)-1)*2;
903 return ((1<<23)-1)*4;
906 /// AcceptWater - Small amount of common code factored out of the following.
908 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
909 std::vector<MachineBasicBlock*>::iterator IP) {
910 DOUT << "found water in range\n";
911 // Remove the original WaterList entry; we want subsequent
912 // insertions in this vicinity to go after the one we're
913 // about to insert. This considerably reduces the number
914 // of times we have to move the same CPE more than once.
916 // CPE goes before following block (NewMBB).
917 return next(MachineFunction::iterator(WaterBB));
920 /// LookForWater - look for an existing entry in the WaterList in which
921 /// we can place the CPE referenced from U so it's within range of U's MI.
922 /// Returns true if found, false if not. If it returns true, *NewMBB
923 /// is set to the WaterList entry.
924 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
925 /// water that will not introduce padding to water that will; within each
926 /// group, prefer the water that's farthest away.
927 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
928 MachineBasicBlock** NewMBB) {
929 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
930 MachineBasicBlock* WaterBBThatWouldPad = NULL;
931 if (!WaterList.empty()) {
932 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
933 B = WaterList.begin();; --IP) {
934 MachineBasicBlock* WaterBB = *IP;
935 if (WaterIsInRange(UserOffset, WaterBB, U)) {
936 unsigned WBBId = WaterBB->getNumber();
938 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
939 // This is valid Water, but would introduce padding. Remember
940 // it in case we don't find any Water that doesn't do this.
941 if (!WaterBBThatWouldPad) {
942 WaterBBThatWouldPad = WaterBB;
946 *NewMBB = AcceptWater(WaterBB, IP);
954 if (isThumb && WaterBBThatWouldPad) {
955 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
961 /// CreateNewWater - No existing WaterList entry will work for
962 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
963 /// block is used if in range, and the conditional branch munged so control
964 /// flow is correct. Otherwise the block is split to create a hole with an
965 /// unconditional branch around it. In either case *NewMBB is set to a
966 /// block following which the new island can be inserted (the WaterList
967 /// is not adjusted).
969 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
970 unsigned UserOffset, MachineBasicBlock** NewMBB) {
971 CPUser &U = CPUsers[CPUserIndex];
972 MachineInstr *UserMI = U.MI;
973 MachineInstr *CPEMI = U.CPEMI;
974 MachineBasicBlock *UserMBB = UserMI->getParent();
975 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
976 BBSizes[UserMBB->getNumber()];
977 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
979 // If the use is at the end of the block, or the end of the block
980 // is within range, make new water there. (The addition below is
981 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
982 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
983 // inside OffsetIsInRange.
984 // If the block ends in an unconditional branch already, it is water,
985 // and is known to be out of range, so we'll always be adding a branch.)
986 if (&UserMBB->back() == UserMI ||
987 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
988 U.MaxDisp, U.NegOk, U.IsSoImm)) {
989 DOUT << "Split at end of block\n";
990 if (&UserMBB->back() == UserMI)
991 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
992 *NewMBB = next(MachineFunction::iterator(UserMBB));
993 // Add an unconditional branch from UserMBB to fallthrough block.
994 // Record it for branch lengthening; this new branch will not get out of
995 // range, but if the preceding conditional branch is out of range, the
996 // targets will be exchanged, and the altered branch may be out of
997 // range, so the machinery has to know about it.
998 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
999 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1000 TII->get(UncondBr)).addMBB(*NewMBB);
1001 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1002 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1003 MaxDisp, false, UncondBr));
1004 int delta = isThumb1 ? 2 : 4;
1005 BBSizes[UserMBB->getNumber()] += delta;
1006 AdjustBBOffsetsAfter(UserMBB, delta);
1008 // What a big block. Find a place within the block to split it.
1009 // This is a little tricky on Thumb1 since instructions are 2 bytes
1010 // and constant pool entries are 4 bytes: if instruction I references
1011 // island CPE, and instruction I+1 references CPE', it will
1012 // not work well to put CPE as far forward as possible, since then
1013 // CPE' cannot immediately follow it (that location is 2 bytes
1014 // farther away from I+1 than CPE was from I) and we'd need to create
1015 // a new island. So, we make a first guess, then walk through the
1016 // instructions between the one currently being looked at and the
1017 // possible insertion point, and make sure any other instructions
1018 // that reference CPEs will be able to use the same island area;
1019 // if not, we back up the insertion point.
1021 // The 4 in the following is for the unconditional branch we'll be
1022 // inserting (allows for long branch on Thumb1). Alignment of the
1023 // island is handled inside OffsetIsInRange.
1024 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1025 // This could point off the end of the block if we've already got
1026 // constant pool entries following this block; only the last one is
1027 // in the water list. Back past any possible branches (allow for a
1028 // conditional and a maximally long unconditional).
1029 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1030 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1032 unsigned EndInsertOffset = BaseInsertOffset +
1033 CPEMI->getOperand(2).getImm();
1034 MachineBasicBlock::iterator MI = UserMI;
1036 unsigned CPUIndex = CPUserIndex+1;
1037 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1038 Offset < BaseInsertOffset;
1039 Offset += TII->GetInstSizeInBytes(MI),
1041 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1042 CPUser &U = CPUsers[CPUIndex];
1043 if (!OffsetIsInRange(Offset, EndInsertOffset,
1044 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1045 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1046 EndInsertOffset -= (isThumb1 ? 2 : 4);
1048 // This is overly conservative, as we don't account for CPEMIs
1049 // being reused within the block, but it doesn't matter much.
1050 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1054 DOUT << "Split in middle of big block\n";
1055 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1059 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1060 /// is out-of-range. If so, pick up the constant pool value and move it some
1061 /// place in-range. Return true if we changed any addresses (thus must run
1062 /// another pass of branch lengthening), false otherwise.
1063 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1064 unsigned CPUserIndex) {
1065 CPUser &U = CPUsers[CPUserIndex];
1066 MachineInstr *UserMI = U.MI;
1067 MachineInstr *CPEMI = U.CPEMI;
1068 unsigned CPI = CPEMI->getOperand(1).getIndex();
1069 unsigned Size = CPEMI->getOperand(2).getImm();
1070 MachineBasicBlock *NewMBB;
1071 // Compute this only once, it's expensive. The 4 or 8 is the value the
1072 // hardware keeps in the PC (2 insns ahead of the reference).
1073 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1075 // See if the current entry is within range, or there is a clone of it
1077 int result = LookForExistingCPEntry(U, UserOffset);
1078 if (result==1) return false;
1079 else if (result==2) return true;
1081 // No existing clone of this CPE is within range.
1082 // We will be generating a new clone. Get a UID for it.
1083 unsigned ID = AFI->createConstPoolEntryUId();
1085 // Look for water where we can place this CPE. We look for the farthest one
1086 // away that will work. Forward references only for now (although later
1087 // we might find some that are backwards).
1089 if (!LookForWater(U, UserOffset, &NewMBB)) {
1091 DOUT << "No water found\n";
1092 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1095 // Okay, we know we can put an island before NewMBB now, do it!
1096 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1097 MF.insert(NewMBB, NewIsland);
1099 // Update internal data structures to account for the newly inserted MBB.
1100 UpdateForInsertedWaterBlock(NewIsland);
1102 // Decrement the old entry, and remove it if refcount becomes 0.
1103 DecrementOldEntry(CPI, CPEMI);
1105 // Now that we have an island to add the CPE to, clone the original CPE and
1106 // add it to the island.
1107 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1108 TII->get(ARM::CONSTPOOL_ENTRY))
1109 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1110 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1113 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1114 // Compensate for .align 2 in thumb mode.
1115 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1117 // Increase the size of the island block to account for the new entry.
1118 BBSizes[NewIsland->getNumber()] += Size;
1119 AdjustBBOffsetsAfter(NewIsland, Size);
1121 // Finally, change the CPI in the instruction operand to be ID.
1122 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1123 if (UserMI->getOperand(i).isCPI()) {
1124 UserMI->getOperand(i).setIndex(ID);
1128 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1133 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1134 /// sizes and offsets of impacted basic blocks.
1135 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1136 MachineBasicBlock *CPEBB = CPEMI->getParent();
1137 unsigned Size = CPEMI->getOperand(2).getImm();
1138 CPEMI->eraseFromParent();
1139 BBSizes[CPEBB->getNumber()] -= Size;
1140 // All succeeding offsets have the current size value added in, fix this.
1141 if (CPEBB->empty()) {
1142 // In thumb1 mode, the size of island may be padded by two to compensate for
1143 // the alignment requirement. Then it will now be 2 when the block is
1144 // empty, so fix this.
1145 // All succeeding offsets have the current size value added in, fix this.
1146 if (BBSizes[CPEBB->getNumber()] != 0) {
1147 Size += BBSizes[CPEBB->getNumber()];
1148 BBSizes[CPEBB->getNumber()] = 0;
1151 AdjustBBOffsetsAfter(CPEBB, -Size);
1152 // An island has only one predecessor BB and one successor BB. Check if
1153 // this BB's predecessor jumps directly to this BB's successor. This
1154 // shouldn't happen currently.
1155 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1156 // FIXME: remove the empty blocks after all the work is done?
1159 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1161 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1162 unsigned MadeChange = false;
1163 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1164 std::vector<CPEntry> &CPEs = CPEntries[i];
1165 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1166 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1167 RemoveDeadCPEMI(CPEs[j].CPEMI);
1168 CPEs[j].CPEMI = NULL;
1176 /// BBIsInRange - Returns true if the distance between specific MI and
1177 /// specific BB can fit in MI's displacement field.
1178 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1180 unsigned PCAdj = isThumb ? 4 : 8;
1181 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1182 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1184 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1185 << " from BB#" << MI->getParent()->getNumber()
1186 << " max delta=" << MaxDisp
1187 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1188 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1190 if (BrOffset <= DestOffset) {
1191 // Branch before the Dest.
1192 if (DestOffset-BrOffset <= MaxDisp)
1195 if (BrOffset-DestOffset <= MaxDisp)
1201 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1202 /// away to fit in its displacement field.
1203 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1204 MachineInstr *MI = Br.MI;
1205 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1207 // Check to see if the DestBB is already in-range.
1208 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1212 return FixUpUnconditionalBr(MF, Br);
1213 return FixUpConditionalBr(MF, Br);
1216 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1217 /// too far away to fit in its displacement field. If the LR register has been
1218 /// spilled in the epilogue, then we can use BL to implement a far jump.
1219 /// Otherwise, add an intermediate branch instruction to a branch.
1221 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1222 MachineInstr *MI = Br.MI;
1223 MachineBasicBlock *MBB = MI->getParent();
1225 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1227 // Use BL to implement far jump.
1228 Br.MaxDisp = (1 << 21) * 2;
1229 MI->setDesc(TII->get(ARM::tBfar));
1230 BBSizes[MBB->getNumber()] += 2;
1231 AdjustBBOffsetsAfter(MBB, 2);
1235 DOUT << " Changed B to long jump " << *MI;
1240 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1241 /// far away to fit in its displacement field. It is converted to an inverse
1242 /// conditional branch + an unconditional branch to the destination.
1244 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1245 MachineInstr *MI = Br.MI;
1246 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1248 // Add an unconditional branch to the destination and invert the branch
1249 // condition to jump over it:
1255 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1256 CC = ARMCC::getOppositeCondition(CC);
1257 unsigned CCReg = MI->getOperand(2).getReg();
1259 // If the branch is at the end of its MBB and that has a fall-through block,
1260 // direct the updated conditional branch to the fall-through block. Otherwise,
1261 // split the MBB before the next instruction.
1262 MachineBasicBlock *MBB = MI->getParent();
1263 MachineInstr *BMI = &MBB->back();
1264 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1268 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1269 BMI->getOpcode() == Br.UncondBr) {
1270 // Last MI in the BB is an unconditional branch. Can we simply invert the
1271 // condition and swap destinations:
1277 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1278 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1279 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
1280 BMI->getOperand(0).setMBB(DestBB);
1281 MI->getOperand(0).setMBB(NewDest);
1282 MI->getOperand(1).setImm(CC);
1289 SplitBlockBeforeInstr(MI);
1290 // No need for the branch to the next block. We're adding an unconditional
1291 // branch to the destination.
1292 int delta = TII->GetInstSizeInBytes(&MBB->back());
1293 BBSizes[MBB->getNumber()] -= delta;
1294 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1295 AdjustBBOffsetsAfter(SplitBB, -delta);
1296 MBB->back().eraseFromParent();
1297 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1299 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1301 DOUT << " Insert B to BB#" << DestBB->getNumber()
1302 << " also invert condition and change dest. to BB#"
1303 << NextBB->getNumber() << "\n";
1305 // Insert a new conditional branch and a new unconditional branch.
1306 // Also update the ImmBranch as well as adding a new entry for the new branch.
1307 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1308 TII->get(MI->getOpcode()))
1309 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1310 Br.MI = &MBB->back();
1311 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1312 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1313 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1314 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1315 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1317 // Remove the old conditional branch. It may or may not still be in MBB.
1318 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1319 MI->eraseFromParent();
1321 // The net size change is an addition of one unconditional branch.
1322 int delta = TII->GetInstSizeInBytes(&MBB->back());
1323 AdjustBBOffsetsAfter(MBB, delta);
1327 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1328 /// LR / restores LR to pc.
1329 bool ARMConstantIslands::UndoLRSpillRestore() {
1330 bool MadeChange = false;
1331 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1332 MachineInstr *MI = PushPopMIs[i];
1333 if (MI->getOpcode() == ARM::tPOP_RET &&
1334 MI->getOperand(0).getReg() == ARM::PC &&
1335 MI->getNumExplicitOperands() == 1) {
1336 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1337 MI->eraseFromParent();
1344 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1345 bool MadeChange = false;
1347 // FIXME: After the tables are shrunk, can we get rid some of the
1348 // constantpool tables?
1349 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1350 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1351 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1352 MachineInstr *MI = T2JumpTables[i];
1353 const TargetInstrDesc &TID = MI->getDesc();
1354 unsigned NumOps = TID.getNumOperands();
1355 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1356 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1357 unsigned JTI = JTOP.getIndex();
1358 assert(JTI < JT.size());
1361 bool HalfWordOk = true;
1362 unsigned JTOffset = GetOffsetOf(MI) + 4;
1363 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1364 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1365 MachineBasicBlock *MBB = JTBBs[j];
1366 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1367 // Negative offset is not ok. FIXME: We should change BB layout to make
1368 // sure all the branches are forward.
1369 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1371 unsigned TBHLimit = ((1<<16)-1)*2;
1372 if (STI->isTargetDarwin())
1373 TBHLimit >>= 1; // FIXME: Work around an assembler bug.
1374 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1376 if (!ByteOk && !HalfWordOk)
1380 if (ByteOk || HalfWordOk) {
1381 MachineBasicBlock *MBB = MI->getParent();
1382 unsigned BaseReg = MI->getOperand(0).getReg();
1383 bool BaseRegKill = MI->getOperand(0).isKill();
1386 unsigned IdxReg = MI->getOperand(1).getReg();
1387 bool IdxRegKill = MI->getOperand(1).isKill();
1388 MachineBasicBlock::iterator PrevI = MI;
1389 if (PrevI == MBB->begin())
1392 MachineInstr *AddrMI = --PrevI;
1394 // Examine the instruction that calculate the jumptable entry address.
1395 // If it's not the one just before the t2BR_JT, we won't delete it, then
1396 // it's not worth doing the optimization.
1397 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1398 const MachineOperand &MO = AddrMI->getOperand(k);
1399 if (!MO.isReg() || !MO.getReg())
1401 if (MO.isDef() && MO.getReg() != BaseReg) {
1405 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1413 // The previous instruction should be a t2LEApcrelJT, we want to delete
1415 MachineInstr *LeaMI = --PrevI;
1416 if (LeaMI->getOpcode() != ARM::t2LEApcrelJT ||
1417 LeaMI->getOperand(0).getReg() != BaseReg)
1423 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1424 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1425 .addReg(IdxReg, getKillRegState(IdxRegKill))
1426 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1427 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1428 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1429 // is 2-byte aligned. For now, asm printer will fix it up.
1430 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1431 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1432 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1433 OrigSize += TII->GetInstSizeInBytes(MI);
1435 AddrMI->eraseFromParent();
1436 LeaMI->eraseFromParent();
1437 MI->eraseFromParent();
1439 int delta = OrigSize - NewSize;
1440 BBSizes[MBB->getNumber()] -= delta;
1441 AdjustBBOffsetsAfter(MBB, -delta);