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/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/Statistic.h"
38 STATISTIC(NumCPEs, "Number of constpool entries");
39 STATISTIC(NumSplit, "Number of uncond branches inserted");
40 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42 STATISTIC(NumTBs, "Number of table branches generated");
43 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
44 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
47 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
48 /// requires constant pool entries to be scattered among the instructions
49 /// inside a function. To do this, it completely ignores the normal LLVM
50 /// constant pool; instead, it places constants wherever it feels like with
51 /// special instructions.
53 /// The terminology used in this pass includes:
54 /// Islands - Clumps of constants placed in the function.
55 /// Water - Potential places where an island could be formed.
56 /// CPE - A constant pool entry that has been placed somewhere, which
57 /// tracks a list of users.
58 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
59 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
60 /// by MBB Number. The two-byte pads required for Thumb alignment are
61 /// counted as part of the following block (i.e., the offset and size for
62 /// a padded block will both be ==2 mod 4).
63 std::vector<unsigned> BBSizes;
65 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
66 /// The two-byte pads required for Thumb alignment are counted as part of
67 /// the following block.
68 std::vector<unsigned> BBOffsets;
70 /// WaterList - A sorted list of basic blocks where islands could be placed
71 /// (i.e. blocks that don't fall through to the following block, due
72 /// to a return, unreachable, or unconditional branch).
73 std::vector<MachineBasicBlock*> WaterList;
75 /// NewWaterList - The subset of WaterList that was created since the
76 /// previous iteration by inserting unconditional branches.
77 SmallSet<MachineBasicBlock*, 4> NewWaterList;
79 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
81 /// CPUser - One user of a constant pool, keeping the machine instruction
82 /// pointer, the constant pool being referenced, and the max displacement
83 /// allowed from the instruction to the CP. The HighWaterMark records the
84 /// highest basic block where a new CPEntry can be placed. To ensure this
85 /// pass terminates, the CP entries are initially placed at the end of the
86 /// function and then move monotonically to lower addresses. The
87 /// exception to this rule is when the current CP entry for a particular
88 /// CPUser is out of range, but there is another CP entry for the same
89 /// constant value in range. We want to use the existing in-range CP
90 /// entry, but if it later moves out of range, the search for new water
91 /// should resume where it left off. The HighWaterMark is used to record
96 MachineBasicBlock *HighWaterMark;
100 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
101 bool neg, bool soimm)
102 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
103 HighWaterMark = CPEMI->getParent();
107 /// CPUsers - Keep track of all of the machine instructions that use various
108 /// constant pools and their max displacement.
109 std::vector<CPUser> CPUsers;
111 /// CPEntry - One per constant pool entry, keeping the machine instruction
112 /// pointer, the constpool index, and the number of CPUser's which
113 /// reference this entry.
118 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
119 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
122 /// CPEntries - Keep track of all of the constant pool entry machine
123 /// instructions. For each original constpool index (i.e. those that
124 /// existed upon entry to this pass), it keeps a vector of entries.
125 /// Original elements are cloned as we go along; the clones are
126 /// put in the vector of the original element, but have distinct CPIs.
127 std::vector<std::vector<CPEntry> > CPEntries;
129 /// ImmBranch - One per immediate branch, keeping the machine instruction
130 /// pointer, conditional or unconditional, the max displacement,
131 /// and (if isCond is true) the corresponding unconditional branch
135 unsigned MaxDisp : 31;
138 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
139 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
142 /// ImmBranches - Keep track of all the immediate branch instructions.
144 std::vector<ImmBranch> ImmBranches;
146 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
148 SmallVector<MachineInstr*, 4> PushPopMIs;
150 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
151 SmallVector<MachineInstr*, 4> T2JumpTables;
153 /// HasFarJump - True if any far jump instruction has been emitted during
154 /// the branch fix up pass.
157 const TargetInstrInfo *TII;
158 const ARMSubtarget *STI;
159 ARMFunctionInfo *AFI;
165 ARMConstantIslands() : MachineFunctionPass(&ID) {}
167 virtual bool runOnMachineFunction(MachineFunction &MF);
169 virtual const char *getPassName() const {
170 return "ARM constant island placement and branch shortening pass";
174 void DoInitialPlacement(MachineFunction &MF,
175 std::vector<MachineInstr*> &CPEMIs);
176 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
177 void InitialFunctionScan(MachineFunction &MF,
178 const std::vector<MachineInstr*> &CPEMIs);
179 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
180 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
181 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
182 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
183 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
184 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
185 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
186 MachineBasicBlock *&NewMBB);
187 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
188 void RemoveDeadCPEMI(MachineInstr *CPEMI);
189 bool RemoveUnusedCPEntries();
190 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
191 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
192 bool DoDump = false);
193 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
195 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
196 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
197 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
198 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
199 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
200 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
201 bool UndoLRSpillRestore();
202 bool OptimizeThumb2Instructions(MachineFunction &MF);
203 bool OptimizeThumb2Branches(MachineFunction &MF);
204 bool OptimizeThumb2JumpTables(MachineFunction &MF);
206 unsigned GetOffsetOf(MachineInstr *MI) const;
208 void verify(MachineFunction &MF);
210 char ARMConstantIslands::ID = 0;
213 /// verify - check BBOffsets, BBSizes, alignment of islands
214 void ARMConstantIslands::verify(MachineFunction &MF) {
215 assert(BBOffsets.size() == BBSizes.size());
216 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
217 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
221 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
223 MachineBasicBlock *MBB = MBBI;
225 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
226 unsigned MBBId = MBB->getNumber();
227 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
228 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
234 /// print block size and offset information - debugging
235 void ARMConstantIslands::dumpBBs() {
236 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
237 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
238 << " size " << BBSizes[J] << "\n");
242 /// createARMConstantIslandPass - returns an instance of the constpool
244 FunctionPass *llvm::createARMConstantIslandPass() {
245 return new ARMConstantIslands();
248 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
249 MachineConstantPool &MCP = *MF.getConstantPool();
251 TII = MF.getTarget().getInstrInfo();
252 AFI = MF.getInfo<ARMFunctionInfo>();
253 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
255 isThumb = AFI->isThumbFunction();
256 isThumb1 = AFI->isThumb1OnlyFunction();
257 isThumb2 = AFI->isThumb2Function();
261 // Renumber all of the machine basic blocks in the function, guaranteeing that
262 // the numbers agree with the position of the block in the function.
265 // Thumb1 functions containing constant pools get 4-byte alignment.
266 // This is so we can keep exact track of where the alignment padding goes.
268 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
270 AFI->setAlign(isThumb1 ? 1U : 2U);
272 // Perform the initial placement of the constant pool entries. To start with,
273 // we put them all at the end of the function.
274 std::vector<MachineInstr*> CPEMIs;
275 if (!MCP.isEmpty()) {
276 DoInitialPlacement(MF, CPEMIs);
281 /// The next UID to take is the first unused one.
282 AFI->initConstPoolEntryUId(CPEMIs.size());
284 // Do the initial scan of the function, building up information about the
285 // sizes of each block, the location of all the water, and finding all of the
286 // constant pool users.
287 InitialFunctionScan(MF, CPEMIs);
290 /// Remove dead constant pool entries.
291 RemoveUnusedCPEntries();
293 // Iteratively place constant pool entries and fix up branches until there
295 bool MadeChange = false;
296 unsigned NoCPIters = 0, NoBRIters = 0;
298 bool CPChange = false;
299 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
300 CPChange |= HandleConstantPoolUser(MF, i);
301 if (CPChange && ++NoCPIters > 30)
302 llvm_unreachable("Constant Island pass failed to converge!");
305 // Clear NewWaterList now. If we split a block for branches, it should
306 // appear as "new water" for the next iteration of constant pool placement.
307 NewWaterList.clear();
309 bool BRChange = false;
310 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
311 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
312 if (BRChange && ++NoBRIters > 30)
313 llvm_unreachable("Branch Fix Up pass failed to converge!");
316 if (!CPChange && !BRChange)
321 // Shrink 32-bit Thumb2 branch, load, and store instructions.
323 MadeChange |= OptimizeThumb2Instructions(MF);
325 // After a while, this might be made debug-only, but it is not expensive.
328 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
329 // Undo the spill / restore of LR if possible.
330 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
331 MadeChange |= UndoLRSpillRestore();
340 T2JumpTables.clear();
345 /// DoInitialPlacement - Perform the initial placement of the constant pool
346 /// entries. To start with, we put them all at the end of the function.
347 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
348 std::vector<MachineInstr*> &CPEMIs) {
349 // Create the basic block to hold the CPE's.
350 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
353 // Add all of the constants from the constant pool to the end block, use an
354 // identity mapping of CPI's to CPE's.
355 const std::vector<MachineConstantPoolEntry> &CPs =
356 MF.getConstantPool()->getConstants();
358 const TargetData &TD = *MF.getTarget().getTargetData();
359 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
360 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
361 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
362 // we would have to pad them out or something so that instructions stay
364 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
365 MachineInstr *CPEMI =
366 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
367 .addImm(i).addConstantPoolIndex(i).addImm(Size);
368 CPEMIs.push_back(CPEMI);
370 // Add a new CPEntry, but no corresponding CPUser yet.
371 std::vector<CPEntry> CPEs;
372 CPEs.push_back(CPEntry(CPEMI, i));
373 CPEntries.push_back(CPEs);
375 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
380 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
381 /// into the block immediately after it.
382 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
383 // Get the next machine basic block in the function.
384 MachineFunction::iterator MBBI = MBB;
385 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
388 MachineBasicBlock *NextBB = next(MBBI);
389 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
390 E = MBB->succ_end(); I != E; ++I)
397 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
398 /// look up the corresponding CPEntry.
399 ARMConstantIslands::CPEntry
400 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
401 const MachineInstr *CPEMI) {
402 std::vector<CPEntry> &CPEs = CPEntries[CPI];
403 // Number of entries per constpool index should be small, just do a
405 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
406 if (CPEs[i].CPEMI == CPEMI)
412 /// InitialFunctionScan - Do the initial scan of the function, building up
413 /// information about the sizes of each block, the location of all the water,
414 /// and finding all of the constant pool users.
415 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
416 const std::vector<MachineInstr*> &CPEMIs) {
418 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
420 MachineBasicBlock &MBB = *MBBI;
422 // If this block doesn't fall through into the next MBB, then this is
423 // 'water' that a constant pool island could be placed.
424 if (!BBHasFallthrough(&MBB))
425 WaterList.push_back(&MBB);
427 unsigned MBBSize = 0;
428 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
430 // Add instruction size to MBBSize.
431 MBBSize += TII->GetInstSizeInBytes(I);
433 int Opc = I->getOpcode();
434 if (I->getDesc().isBranch()) {
441 continue; // Ignore other JT branches
443 // A Thumb1 table jump may involve padding; for the offsets to
444 // be right, functions containing these must be 4-byte aligned.
446 if ((Offset+MBBSize)%4 != 0)
447 // FIXME: Add a pseudo ALIGN instruction instead.
448 MBBSize += 2; // padding
449 continue; // Does not get an entry in ImmBranches
451 T2JumpTables.push_back(I);
452 continue; // Does not get an entry in ImmBranches
483 // Record this immediate branch.
484 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
485 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
488 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
489 PushPopMIs.push_back(I);
491 if (Opc == ARM::CONSTPOOL_ENTRY)
494 // Scan the instructions for constant pool operands.
495 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
496 if (I->getOperand(op).isCPI()) {
497 // We found one. The addressing mode tells us the max displacement
498 // from the PC that this instruction permits.
500 // Basic size info comes from the TSFlags field.
504 bool IsSoImm = false;
508 llvm_unreachable("Unknown addressing mode for CP reference!");
511 // Taking the address of a CP entry.
513 // This takes a SoImm, which is 8 bit immediate rotated. We'll
514 // pretend the maximum offset is 255 * 4. Since each instruction
515 // 4 byte wide, this is always correct. We'llc heck for other
516 // displacements that fits in a SoImm as well.
522 case ARM::t2LEApcrel:
534 Bits = 12; // +-offset_12
541 Scale = 4; // +(offset_8*4)
547 Scale = 4; // +-(offset_8*4)
552 // Remember that this is a user of a CP entry.
553 unsigned CPI = I->getOperand(op).getIndex();
554 MachineInstr *CPEMI = CPEMIs[CPI];
555 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
556 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
558 // Increment corresponding CPEntry reference count.
559 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
560 assert(CPE && "Cannot find a corresponding CPEntry!");
563 // Instructions can only use one CP entry, don't bother scanning the
564 // rest of the operands.
569 // In thumb mode, if this block is a constpool island, we may need padding
570 // so it's aligned on 4 byte boundary.
573 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
577 BBSizes.push_back(MBBSize);
578 BBOffsets.push_back(Offset);
583 /// GetOffsetOf - Return the current offset of the specified machine instruction
584 /// from the start of the function. This offset changes as stuff is moved
585 /// around inside the function.
586 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
587 MachineBasicBlock *MBB = MI->getParent();
589 // The offset is composed of two things: the sum of the sizes of all MBB's
590 // before this instruction's block, and the offset from the start of the block
592 unsigned Offset = BBOffsets[MBB->getNumber()];
594 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
595 // alignment padding, and compensate if so.
597 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
601 // Sum instructions before MI in MBB.
602 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
603 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
604 if (&*I == MI) return Offset;
605 Offset += TII->GetInstSizeInBytes(I);
609 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
611 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
612 const MachineBasicBlock *RHS) {
613 return LHS->getNumber() < RHS->getNumber();
616 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
617 /// machine function, it upsets all of the block numbers. Renumber the blocks
618 /// and update the arrays that parallel this numbering.
619 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
620 // Renumber the MBB's to keep them consequtive.
621 NewBB->getParent()->RenumberBlocks(NewBB);
623 // Insert a size into BBSizes to align it properly with the (newly
624 // renumbered) block numbers.
625 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
627 // Likewise for BBOffsets.
628 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
630 // Next, update WaterList. Specifically, we need to add NewMBB as having
631 // available water after it.
633 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
635 WaterList.insert(IP, NewBB);
639 /// Split the basic block containing MI into two blocks, which are joined by
640 /// an unconditional branch. Update data structures and renumber blocks to
641 /// account for this change and returns the newly created block.
642 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
643 MachineBasicBlock *OrigBB = MI->getParent();
644 MachineFunction &MF = *OrigBB->getParent();
646 // Create a new MBB for the code after the OrigBB.
647 MachineBasicBlock *NewBB =
648 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
649 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
650 MF.insert(MBBI, NewBB);
652 // Splice the instructions starting with MI over to NewBB.
653 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
655 // Add an unconditional branch from OrigBB to NewBB.
656 // Note the new unconditional branch is not being recorded.
657 // There doesn't seem to be meaningful DebugInfo available; this doesn't
658 // correspond to anything in the source.
659 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
660 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
663 // Update the CFG. All succs of OrigBB are now succs of NewBB.
664 while (!OrigBB->succ_empty()) {
665 MachineBasicBlock *Succ = *OrigBB->succ_begin();
666 OrigBB->removeSuccessor(Succ);
667 NewBB->addSuccessor(Succ);
669 // This pass should be run after register allocation, so there should be no
670 // PHI nodes to update.
671 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
672 && "PHI nodes should be eliminated by now!");
675 // OrigBB branches to NewBB.
676 OrigBB->addSuccessor(NewBB);
678 // Update internal data structures to account for the newly inserted MBB.
679 // This is almost the same as UpdateForInsertedWaterBlock, except that
680 // the Water goes after OrigBB, not NewBB.
681 MF.RenumberBlocks(NewBB);
683 // Insert a size into BBSizes to align it properly with the (newly
684 // renumbered) block numbers.
685 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
687 // Likewise for BBOffsets.
688 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
690 // Next, update WaterList. Specifically, we need to add OrigMBB as having
691 // available water after it (but not if it's already there, which happens
692 // when splitting before a conditional branch that is followed by an
693 // unconditional branch - in that case we want to insert NewBB).
695 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
697 MachineBasicBlock* WaterBB = *IP;
698 if (WaterBB == OrigBB)
699 WaterList.insert(next(IP), NewBB);
701 WaterList.insert(IP, OrigBB);
702 NewWaterList.insert(OrigBB);
704 // Figure out how large the first NewMBB is. (It cannot
705 // contain a constpool_entry or tablejump.)
706 unsigned NewBBSize = 0;
707 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
709 NewBBSize += TII->GetInstSizeInBytes(I);
711 unsigned OrigBBI = OrigBB->getNumber();
712 unsigned NewBBI = NewBB->getNumber();
713 // Set the size of NewBB in BBSizes.
714 BBSizes[NewBBI] = NewBBSize;
716 // We removed instructions from UserMBB, subtract that off from its size.
717 // Add 2 or 4 to the block to count the unconditional branch we added to it.
718 int delta = isThumb1 ? 2 : 4;
719 BBSizes[OrigBBI] -= NewBBSize - delta;
721 // ...and adjust BBOffsets for NewBB accordingly.
722 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
724 // All BBOffsets following these blocks must be modified.
725 AdjustBBOffsetsAfter(NewBB, delta);
730 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
731 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
732 /// constant pool entry).
733 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
734 unsigned TrialOffset, unsigned MaxDisp,
735 bool NegativeOK, bool IsSoImm) {
736 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
737 // purposes of the displacement computation; compensate for that here.
738 // Effectively, the valid range of displacements is 2 bytes smaller for such
740 unsigned TotalAdj = 0;
741 if (isThumb && UserOffset%4 !=0) {
745 // CPEs will be rounded up to a multiple of 4.
746 if (isThumb && TrialOffset%4 != 0) {
751 // In Thumb2 mode, later branch adjustments can shift instructions up and
752 // cause alignment change. In the worst case scenario this can cause the
753 // user's effective address to be subtracted by 2 and the CPE's address to
755 if (isThumb2 && TotalAdj != 4)
756 MaxDisp -= (4 - TotalAdj);
758 if (UserOffset <= TrialOffset) {
759 // User before the Trial.
760 if (TrialOffset - UserOffset <= MaxDisp)
762 // FIXME: Make use full range of soimm values.
763 } else if (NegativeOK) {
764 if (UserOffset - TrialOffset <= MaxDisp)
766 // FIXME: Make use full range of soimm values.
771 /// WaterIsInRange - Returns true if a CPE placed after the specified
772 /// Water (a basic block) will be in range for the specific MI.
774 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
775 MachineBasicBlock* Water, CPUser &U) {
776 unsigned MaxDisp = U.MaxDisp;
777 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
778 BBSizes[Water->getNumber()];
780 // If the CPE is to be inserted before the instruction, that will raise
781 // the offset of the instruction.
782 if (CPEOffset < UserOffset)
783 UserOffset += U.CPEMI->getOperand(2).getImm();
785 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
788 /// CPEIsInRange - Returns true if the distance between specific MI and
789 /// specific ConstPool entry instruction can fit in MI's displacement field.
790 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
791 MachineInstr *CPEMI, unsigned MaxDisp,
792 bool NegOk, bool DoDump) {
793 unsigned CPEOffset = GetOffsetOf(CPEMI);
794 assert(CPEOffset%4 == 0 && "Misaligned CPE");
797 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
798 << " max delta=" << MaxDisp
799 << " insn address=" << UserOffset
800 << " CPE address=" << CPEOffset
801 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
804 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
808 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
809 /// unconditionally branches to its only successor.
810 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
811 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
814 MachineBasicBlock *Succ = *MBB->succ_begin();
815 MachineBasicBlock *Pred = *MBB->pred_begin();
816 MachineInstr *PredMI = &Pred->back();
817 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
818 || PredMI->getOpcode() == ARM::t2B)
819 return PredMI->getOperand(0).getMBB() == Succ;
824 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
826 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
827 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
829 BBOffsets[i] += delta;
830 // If some existing blocks have padding, adjust the padding as needed, a
831 // bit tricky. delta can be negative so don't use % on that.
834 MachineBasicBlock *MBB = MBBI;
836 // Constant pool entries require padding.
837 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
838 unsigned OldOffset = BBOffsets[i] - delta;
839 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
843 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
844 // remove existing padding
849 // Thumb1 jump tables require padding. They should be at the end;
850 // following unconditional branches are removed by AnalyzeBranch.
851 MachineInstr *ThumbJTMI = prior(MBB->end());
852 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
853 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
854 unsigned OldMIOffset = NewMIOffset - delta;
855 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
856 // remove existing padding
859 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
872 /// DecrementOldEntry - find the constant pool entry with index CPI
873 /// and instruction CPEMI, and decrement its refcount. If the refcount
874 /// becomes 0 remove the entry and instruction. Returns true if we removed
875 /// the entry, false if we didn't.
877 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
878 // Find the old entry. Eliminate it if it is no longer used.
879 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
880 assert(CPE && "Unexpected!");
881 if (--CPE->RefCount == 0) {
882 RemoveDeadCPEMI(CPEMI);
890 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
891 /// if not, see if an in-range clone of the CPE is in range, and if so,
892 /// change the data structures so the user references the clone. Returns:
893 /// 0 = no existing entry found
894 /// 1 = entry found, and there were no code insertions or deletions
895 /// 2 = entry found, and there were code insertions or deletions
896 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
898 MachineInstr *UserMI = U.MI;
899 MachineInstr *CPEMI = U.CPEMI;
901 // Check to see if the CPE is already in-range.
902 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
903 DEBUG(errs() << "In range\n");
907 // No. Look for previously created clones of the CPE that are in range.
908 unsigned CPI = CPEMI->getOperand(1).getIndex();
909 std::vector<CPEntry> &CPEs = CPEntries[CPI];
910 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
911 // We already tried this one
912 if (CPEs[i].CPEMI == CPEMI)
914 // Removing CPEs can leave empty entries, skip
915 if (CPEs[i].CPEMI == NULL)
917 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
918 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
919 << CPEs[i].CPI << "\n");
920 // Point the CPUser node to the replacement
921 U.CPEMI = CPEs[i].CPEMI;
922 // Change the CPI in the instruction operand to refer to the clone.
923 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
924 if (UserMI->getOperand(j).isCPI()) {
925 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
928 // Adjust the refcount of the clone...
930 // ...and the original. If we didn't remove the old entry, none of the
931 // addresses changed, so we don't need another pass.
932 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
938 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
939 /// the specific unconditional branch instruction.
940 static inline unsigned getUnconditionalBrDisp(int Opc) {
943 return ((1<<10)-1)*2;
945 return ((1<<23)-1)*2;
950 return ((1<<23)-1)*4;
953 /// LookForWater - Look for an existing entry in the WaterList in which
954 /// we can place the CPE referenced from U so it's within range of U's MI.
955 /// Returns true if found, false if not. If it returns true, WaterIter
956 /// is set to the WaterList entry. For Thumb, prefer water that will not
957 /// introduce padding to water that will. To ensure that this pass
958 /// terminates, the CPE location for a particular CPUser is only allowed to
959 /// move to a lower address, so search backward from the end of the list and
960 /// prefer the first water that is in range.
961 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
962 water_iterator &WaterIter) {
963 if (WaterList.empty())
966 bool FoundWaterThatWouldPad = false;
967 water_iterator IPThatWouldPad;
968 for (water_iterator IP = prior(WaterList.end()),
969 B = WaterList.begin();; --IP) {
970 MachineBasicBlock* WaterBB = *IP;
971 // Check if water is in range and is either at a lower address than the
972 // current "high water mark" or a new water block that was created since
973 // the previous iteration by inserting an unconditional branch. In the
974 // latter case, we want to allow resetting the high water mark back to
975 // this new water since we haven't seen it before. Inserting branches
976 // should be relatively uncommon and when it does happen, we want to be
977 // sure to take advantage of it for all the CPEs near that block, so that
978 // we don't insert more branches than necessary.
979 if (WaterIsInRange(UserOffset, WaterBB, U) &&
980 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
981 NewWaterList.count(WaterBB))) {
982 unsigned WBBId = WaterBB->getNumber();
984 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
985 // This is valid Water, but would introduce padding. Remember
986 // it in case we don't find any Water that doesn't do this.
987 if (!FoundWaterThatWouldPad) {
988 FoundWaterThatWouldPad = true;
999 if (FoundWaterThatWouldPad) {
1000 WaterIter = IPThatWouldPad;
1006 /// CreateNewWater - No existing WaterList entry will work for
1007 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1008 /// block is used if in range, and the conditional branch munged so control
1009 /// flow is correct. Otherwise the block is split to create a hole with an
1010 /// unconditional branch around it. In either case NewMBB is set to a
1011 /// block following which the new island can be inserted (the WaterList
1012 /// is not adjusted).
1013 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1014 unsigned UserOffset,
1015 MachineBasicBlock *&NewMBB) {
1016 CPUser &U = CPUsers[CPUserIndex];
1017 MachineInstr *UserMI = U.MI;
1018 MachineInstr *CPEMI = U.CPEMI;
1019 MachineBasicBlock *UserMBB = UserMI->getParent();
1020 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1021 BBSizes[UserMBB->getNumber()];
1022 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1024 // If the block does not end in an unconditional branch already, and if the
1025 // end of the block is within range, make new water there. (The addition
1026 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1027 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1028 // inside OffsetIsInRange.
1029 if (BBHasFallthrough(UserMBB) &&
1030 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1031 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1032 DEBUG(errs() << "Split at end of block\n");
1033 if (&UserMBB->back() == UserMI)
1034 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1035 NewMBB = next(MachineFunction::iterator(UserMBB));
1036 // Add an unconditional branch from UserMBB to fallthrough block.
1037 // Record it for branch lengthening; this new branch will not get out of
1038 // range, but if the preceding conditional branch is out of range, the
1039 // targets will be exchanged, and the altered branch may be out of
1040 // range, so the machinery has to know about it.
1041 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1042 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1043 TII->get(UncondBr)).addMBB(NewMBB);
1044 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1045 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1046 MaxDisp, false, UncondBr));
1047 int delta = isThumb1 ? 2 : 4;
1048 BBSizes[UserMBB->getNumber()] += delta;
1049 AdjustBBOffsetsAfter(UserMBB, delta);
1051 // What a big block. Find a place within the block to split it.
1052 // This is a little tricky on Thumb1 since instructions are 2 bytes
1053 // and constant pool entries are 4 bytes: if instruction I references
1054 // island CPE, and instruction I+1 references CPE', it will
1055 // not work well to put CPE as far forward as possible, since then
1056 // CPE' cannot immediately follow it (that location is 2 bytes
1057 // farther away from I+1 than CPE was from I) and we'd need to create
1058 // a new island. So, we make a first guess, then walk through the
1059 // instructions between the one currently being looked at and the
1060 // possible insertion point, and make sure any other instructions
1061 // that reference CPEs will be able to use the same island area;
1062 // if not, we back up the insertion point.
1064 // The 4 in the following is for the unconditional branch we'll be
1065 // inserting (allows for long branch on Thumb1). Alignment of the
1066 // island is handled inside OffsetIsInRange.
1067 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1068 // This could point off the end of the block if we've already got
1069 // constant pool entries following this block; only the last one is
1070 // in the water list. Back past any possible branches (allow for a
1071 // conditional and a maximally long unconditional).
1072 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1073 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1075 unsigned EndInsertOffset = BaseInsertOffset +
1076 CPEMI->getOperand(2).getImm();
1077 MachineBasicBlock::iterator MI = UserMI;
1079 unsigned CPUIndex = CPUserIndex+1;
1080 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1081 Offset < BaseInsertOffset;
1082 Offset += TII->GetInstSizeInBytes(MI),
1084 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1085 CPUser &U = CPUsers[CPUIndex];
1086 if (!OffsetIsInRange(Offset, EndInsertOffset,
1087 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1088 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1089 EndInsertOffset -= (isThumb1 ? 2 : 4);
1091 // This is overly conservative, as we don't account for CPEMIs
1092 // being reused within the block, but it doesn't matter much.
1093 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1097 DEBUG(errs() << "Split in middle of big block\n");
1098 NewMBB = SplitBlockBeforeInstr(prior(MI));
1102 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1103 /// is out-of-range. If so, pick up the constant pool value and move it some
1104 /// place in-range. Return true if we changed any addresses (thus must run
1105 /// another pass of branch lengthening), false otherwise.
1106 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1107 unsigned CPUserIndex) {
1108 CPUser &U = CPUsers[CPUserIndex];
1109 MachineInstr *UserMI = U.MI;
1110 MachineInstr *CPEMI = U.CPEMI;
1111 unsigned CPI = CPEMI->getOperand(1).getIndex();
1112 unsigned Size = CPEMI->getOperand(2).getImm();
1113 // Compute this only once, it's expensive. The 4 or 8 is the value the
1114 // hardware keeps in the PC.
1115 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1117 // See if the current entry is within range, or there is a clone of it
1119 int result = LookForExistingCPEntry(U, UserOffset);
1120 if (result==1) return false;
1121 else if (result==2) return true;
1123 // No existing clone of this CPE is within range.
1124 // We will be generating a new clone. Get a UID for it.
1125 unsigned ID = AFI->createConstPoolEntryUId();
1127 // Look for water where we can place this CPE.
1128 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1129 MachineBasicBlock *NewMBB;
1131 if (LookForWater(U, UserOffset, IP)) {
1132 DEBUG(errs() << "found water in range\n");
1133 MachineBasicBlock *WaterBB = *IP;
1135 // If the original WaterList entry was "new water" on this iteration,
1136 // propagate that to the new island. This is just keeping NewWaterList
1137 // updated to match the WaterList, which will be updated below.
1138 if (NewWaterList.count(WaterBB)) {
1139 NewWaterList.erase(WaterBB);
1140 NewWaterList.insert(NewIsland);
1142 // The new CPE goes before the following block (NewMBB).
1143 NewMBB = next(MachineFunction::iterator(WaterBB));
1147 DEBUG(errs() << "No water found\n");
1148 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1150 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1151 // called while handling branches so that the water will be seen on the
1152 // next iteration for constant pools, but in this context, we don't want
1153 // it. Check for this so it will be removed from the WaterList.
1154 // Also remove any entry from NewWaterList.
1155 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1156 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1157 if (IP != WaterList.end())
1158 NewWaterList.erase(WaterBB);
1160 // We are adding new water. Update NewWaterList.
1161 NewWaterList.insert(NewIsland);
1164 // Remove the original WaterList entry; we want subsequent insertions in
1165 // this vicinity to go after the one we're about to insert. This
1166 // considerably reduces the number of times we have to move the same CPE
1167 // more than once and is also important to ensure the algorithm terminates.
1168 if (IP != WaterList.end())
1169 WaterList.erase(IP);
1171 // Okay, we know we can put an island before NewMBB now, do it!
1172 MF.insert(NewMBB, NewIsland);
1174 // Update internal data structures to account for the newly inserted MBB.
1175 UpdateForInsertedWaterBlock(NewIsland);
1177 // Decrement the old entry, and remove it if refcount becomes 0.
1178 DecrementOldEntry(CPI, CPEMI);
1180 // Now that we have an island to add the CPE to, clone the original CPE and
1181 // add it to the island.
1182 U.HighWaterMark = NewIsland;
1183 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1184 TII->get(ARM::CONSTPOOL_ENTRY))
1185 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1186 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1189 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1190 // Compensate for .align 2 in thumb mode.
1191 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1193 // Increase the size of the island block to account for the new entry.
1194 BBSizes[NewIsland->getNumber()] += Size;
1195 AdjustBBOffsetsAfter(NewIsland, Size);
1197 // Finally, change the CPI in the instruction operand to be ID.
1198 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1199 if (UserMI->getOperand(i).isCPI()) {
1200 UserMI->getOperand(i).setIndex(ID);
1204 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1205 << '\t' << *UserMI);
1210 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1211 /// sizes and offsets of impacted basic blocks.
1212 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1213 MachineBasicBlock *CPEBB = CPEMI->getParent();
1214 unsigned Size = CPEMI->getOperand(2).getImm();
1215 CPEMI->eraseFromParent();
1216 BBSizes[CPEBB->getNumber()] -= Size;
1217 // All succeeding offsets have the current size value added in, fix this.
1218 if (CPEBB->empty()) {
1219 // In thumb1 mode, the size of island may be padded by two to compensate for
1220 // the alignment requirement. Then it will now be 2 when the block is
1221 // empty, so fix this.
1222 // All succeeding offsets have the current size value added in, fix this.
1223 if (BBSizes[CPEBB->getNumber()] != 0) {
1224 Size += BBSizes[CPEBB->getNumber()];
1225 BBSizes[CPEBB->getNumber()] = 0;
1228 AdjustBBOffsetsAfter(CPEBB, -Size);
1229 // An island has only one predecessor BB and one successor BB. Check if
1230 // this BB's predecessor jumps directly to this BB's successor. This
1231 // shouldn't happen currently.
1232 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1233 // FIXME: remove the empty blocks after all the work is done?
1236 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1238 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1239 unsigned MadeChange = false;
1240 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1241 std::vector<CPEntry> &CPEs = CPEntries[i];
1242 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1243 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1244 RemoveDeadCPEMI(CPEs[j].CPEMI);
1245 CPEs[j].CPEMI = NULL;
1253 /// BBIsInRange - Returns true if the distance between specific MI and
1254 /// specific BB can fit in MI's displacement field.
1255 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1257 unsigned PCAdj = isThumb ? 4 : 8;
1258 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1259 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1261 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1262 << " from BB#" << MI->getParent()->getNumber()
1263 << " max delta=" << MaxDisp
1264 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1265 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1267 if (BrOffset <= DestOffset) {
1268 // Branch before the Dest.
1269 if (DestOffset-BrOffset <= MaxDisp)
1272 if (BrOffset-DestOffset <= MaxDisp)
1278 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1279 /// away to fit in its displacement field.
1280 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1281 MachineInstr *MI = Br.MI;
1282 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1284 // Check to see if the DestBB is already in-range.
1285 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1289 return FixUpUnconditionalBr(MF, Br);
1290 return FixUpConditionalBr(MF, Br);
1293 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1294 /// too far away to fit in its displacement field. If the LR register has been
1295 /// spilled in the epilogue, then we can use BL to implement a far jump.
1296 /// Otherwise, add an intermediate branch instruction to a branch.
1298 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1299 MachineInstr *MI = Br.MI;
1300 MachineBasicBlock *MBB = MI->getParent();
1302 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1304 // Use BL to implement far jump.
1305 Br.MaxDisp = (1 << 21) * 2;
1306 MI->setDesc(TII->get(ARM::tBfar));
1307 BBSizes[MBB->getNumber()] += 2;
1308 AdjustBBOffsetsAfter(MBB, 2);
1312 DEBUG(errs() << " Changed B to long jump " << *MI);
1317 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1318 /// far away to fit in its displacement field. It is converted to an inverse
1319 /// conditional branch + an unconditional branch to the destination.
1321 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1322 MachineInstr *MI = Br.MI;
1323 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1325 // Add an unconditional branch to the destination and invert the branch
1326 // condition to jump over it:
1332 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1333 CC = ARMCC::getOppositeCondition(CC);
1334 unsigned CCReg = MI->getOperand(2).getReg();
1336 // If the branch is at the end of its MBB and that has a fall-through block,
1337 // direct the updated conditional branch to the fall-through block. Otherwise,
1338 // split the MBB before the next instruction.
1339 MachineBasicBlock *MBB = MI->getParent();
1340 MachineInstr *BMI = &MBB->back();
1341 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1345 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1346 BMI->getOpcode() == Br.UncondBr) {
1347 // Last MI in the BB is an unconditional branch. Can we simply invert the
1348 // condition and swap destinations:
1354 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1355 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1356 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1358 BMI->getOperand(0).setMBB(DestBB);
1359 MI->getOperand(0).setMBB(NewDest);
1360 MI->getOperand(1).setImm(CC);
1367 SplitBlockBeforeInstr(MI);
1368 // No need for the branch to the next block. We're adding an unconditional
1369 // branch to the destination.
1370 int delta = TII->GetInstSizeInBytes(&MBB->back());
1371 BBSizes[MBB->getNumber()] -= delta;
1372 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1373 AdjustBBOffsetsAfter(SplitBB, -delta);
1374 MBB->back().eraseFromParent();
1375 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1377 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1379 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1380 << " also invert condition and change dest. to BB#"
1381 << NextBB->getNumber() << "\n");
1383 // Insert a new conditional branch and a new unconditional branch.
1384 // Also update the ImmBranch as well as adding a new entry for the new branch.
1385 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1386 TII->get(MI->getOpcode()))
1387 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1388 Br.MI = &MBB->back();
1389 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1390 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1391 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1392 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1393 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1395 // Remove the old conditional branch. It may or may not still be in MBB.
1396 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1397 MI->eraseFromParent();
1399 // The net size change is an addition of one unconditional branch.
1400 int delta = TII->GetInstSizeInBytes(&MBB->back());
1401 AdjustBBOffsetsAfter(MBB, delta);
1405 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1406 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1407 /// to do this if tBfar is not used.
1408 bool ARMConstantIslands::UndoLRSpillRestore() {
1409 bool MadeChange = false;
1410 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1411 MachineInstr *MI = PushPopMIs[i];
1412 // First two operands are predicates, the third is a zero since there
1414 if (MI->getOpcode() == ARM::tPOP_RET &&
1415 MI->getOperand(3).getReg() == ARM::PC &&
1416 MI->getNumExplicitOperands() == 4) {
1417 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1418 MI->eraseFromParent();
1425 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1426 bool MadeChange = false;
1428 // Shrink ADR and LDR from constantpool.
1429 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1430 CPUser &U = CPUsers[i];
1431 unsigned Opcode = U.MI->getOpcode();
1432 unsigned NewOpc = 0;
1437 case ARM::t2LEApcrel:
1438 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1439 NewOpc = ARM::tLEApcrel;
1445 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1446 NewOpc = ARM::tLDRpci;
1456 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1457 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1458 // FIXME: Check if offset is multiple of scale if scale is not 4.
1459 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1460 U.MI->setDesc(TII->get(NewOpc));
1461 MachineBasicBlock *MBB = U.MI->getParent();
1462 BBSizes[MBB->getNumber()] -= 2;
1463 AdjustBBOffsetsAfter(MBB, -2);
1469 MadeChange |= OptimizeThumb2Branches(MF);
1470 MadeChange |= OptimizeThumb2JumpTables(MF);
1474 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1475 bool MadeChange = false;
1477 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1478 ImmBranch &Br = ImmBranches[i];
1479 unsigned Opcode = Br.MI->getOpcode();
1480 unsigned NewOpc = 0;
1499 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1500 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1501 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1502 Br.MI->setDesc(TII->get(NewOpc));
1503 MachineBasicBlock *MBB = Br.MI->getParent();
1504 BBSizes[MBB->getNumber()] -= 2;
1505 AdjustBBOffsetsAfter(MBB, -2);
1515 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1516 /// jumptables when it's possible.
1517 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1518 bool MadeChange = false;
1520 // FIXME: After the tables are shrunk, can we get rid some of the
1521 // constantpool tables?
1522 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1523 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1524 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1525 MachineInstr *MI = T2JumpTables[i];
1526 const TargetInstrDesc &TID = MI->getDesc();
1527 unsigned NumOps = TID.getNumOperands();
1528 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1529 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1530 unsigned JTI = JTOP.getIndex();
1531 assert(JTI < JT.size());
1534 bool HalfWordOk = true;
1535 unsigned JTOffset = GetOffsetOf(MI) + 4;
1536 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1537 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1538 MachineBasicBlock *MBB = JTBBs[j];
1539 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1540 // Negative offset is not ok. FIXME: We should change BB layout to make
1541 // sure all the branches are forward.
1542 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1544 unsigned TBHLimit = ((1<<16)-1)*2;
1545 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1547 if (!ByteOk && !HalfWordOk)
1551 if (ByteOk || HalfWordOk) {
1552 MachineBasicBlock *MBB = MI->getParent();
1553 unsigned BaseReg = MI->getOperand(0).getReg();
1554 bool BaseRegKill = MI->getOperand(0).isKill();
1557 unsigned IdxReg = MI->getOperand(1).getReg();
1558 bool IdxRegKill = MI->getOperand(1).isKill();
1559 MachineBasicBlock::iterator PrevI = MI;
1560 if (PrevI == MBB->begin())
1563 MachineInstr *AddrMI = --PrevI;
1565 // Examine the instruction that calculate the jumptable entry address.
1566 // If it's not the one just before the t2BR_JT, we won't delete it, then
1567 // it's not worth doing the optimization.
1568 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1569 const MachineOperand &MO = AddrMI->getOperand(k);
1570 if (!MO.isReg() || !MO.getReg())
1572 if (MO.isDef() && MO.getReg() != BaseReg) {
1576 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1584 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1585 // to delete it as well.
1586 MachineInstr *LeaMI = --PrevI;
1587 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1588 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1589 LeaMI->getOperand(0).getReg() != BaseReg)
1595 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1596 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1597 .addReg(IdxReg, getKillRegState(IdxRegKill))
1598 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1599 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1600 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1601 // is 2-byte aligned. For now, asm printer will fix it up.
1602 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1603 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1604 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1605 OrigSize += TII->GetInstSizeInBytes(MI);
1607 AddrMI->eraseFromParent();
1608 LeaMI->eraseFromParent();
1609 MI->eraseFromParent();
1611 int delta = OrigSize - NewSize;
1612 BBSizes[MBB->getNumber()] -= delta;
1613 AdjustBBOffsetsAfter(MBB, -delta);