1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function. This is required due to the
12 // limited pc-relative displacements that ARM has.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "Thumb2InstrInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.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"
35 #include "llvm/Support/CommandLine.h"
39 STATISTIC(NumCPEs, "Number of constpool entries");
40 STATISTIC(NumSplit, "Number of uncond branches inserted");
41 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43 STATISTIC(NumTBs, "Number of table branches generated");
44 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
45 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
46 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
47 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
48 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
52 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
53 cl::desc("Adjust basic block layout to better use TB[BH]"));
56 AlignConstantIslands("arm-align-constant-island", cl::Hidden,
57 cl::desc("Align constant islands in code"));
59 /// UnknownPadding - Return the worst case padding that could result from
60 /// unknown offset bits. This does not include alignment padding caused by
61 /// known offset bits.
63 /// @param LogAlign log2(alignment)
64 /// @param KnownBits Number of known low offset bits.
65 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
66 if (KnownBits < LogAlign)
67 return (1u << LogAlign) - (1u << KnownBits);
71 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
72 /// add padding such that:
74 /// 1. The result is aligned to 1 << LogAlign.
76 /// 2. No other value of the unknown bits would require more padding.
78 /// This may add more padding than is required to satisfy just one of the
79 /// constraints. It is necessary to compute alignment this way to guarantee
80 /// that we don't underestimate the padding before an aligned block. If the
81 /// real padding before a block is larger than we think, constant pool entries
82 /// may go out of range.
83 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
85 // Add the worst possible padding that the unknown bits could cause.
86 Offset += UnknownPadding(LogAlign, KnownBits);
88 // Then align the result.
89 return RoundUpToAlignment(Offset, 1u << LogAlign);
93 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
94 /// requires constant pool entries to be scattered among the instructions
95 /// inside a function. To do this, it completely ignores the normal LLVM
96 /// constant pool; instead, it places constants wherever it feels like with
97 /// special instructions.
99 /// The terminology used in this pass includes:
100 /// Islands - Clumps of constants placed in the function.
101 /// Water - Potential places where an island could be formed.
102 /// CPE - A constant pool entry that has been placed somewhere, which
103 /// tracks a list of users.
104 class ARMConstantIslands : public MachineFunctionPass {
105 /// BasicBlockInfo - Information about the offset and size of a single
107 struct BasicBlockInfo {
108 /// Offset - Distance from the beginning of the function to the beginning
109 /// of this basic block.
111 /// The offset is always aligned as required by the basic block.
114 /// Size - Size of the basic block in bytes. If the block contains
115 /// inline assembly, this is a worst case estimate.
117 /// The size does not include any alignment padding whether from the
118 /// beginning of the block, or from an aligned jump table at the end.
121 /// KnownBits - The number of low bits in Offset that are known to be
122 /// exact. The remaining bits of Offset are an upper bound.
125 /// Unalign - When non-zero, the block contains instructions (inline asm)
126 /// of unknown size. The real size may be smaller than Size bytes by a
127 /// multiple of 1 << Unalign.
130 /// PostAlign - When non-zero, the block terminator contains a .align
131 /// directive, so the end of the block is aligned to 1 << PostAlign
135 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
138 /// Compute the number of known offset bits internally to this block.
139 /// This number should be used to predict worst case padding when
140 /// splitting the block.
141 unsigned internalKnownBits() const {
142 return Unalign ? Unalign : KnownBits;
145 /// Compute the offset immediately following this block.
146 unsigned postOffset() const {
147 unsigned PO = Offset + Size;
150 // Add alignment padding from the terminator.
151 return WorstCaseAlign(PO, PostAlign, internalKnownBits());
154 /// Compute the number of known low bits of postOffset. If this block
155 /// contains inline asm, the number of known bits drops to the
156 /// instruction alignment. An aligned terminator may increase the number
158 unsigned postKnownBits() const {
159 return std::max(unsigned(PostAlign), internalKnownBits());
163 std::vector<BasicBlockInfo> BBInfo;
165 /// WaterList - A sorted list of basic blocks where islands could be placed
166 /// (i.e. blocks that don't fall through to the following block, due
167 /// to a return, unreachable, or unconditional branch).
168 std::vector<MachineBasicBlock*> WaterList;
170 /// NewWaterList - The subset of WaterList that was created since the
171 /// previous iteration by inserting unconditional branches.
172 SmallSet<MachineBasicBlock*, 4> NewWaterList;
174 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
176 /// CPUser - One user of a constant pool, keeping the machine instruction
177 /// pointer, the constant pool being referenced, and the max displacement
178 /// allowed from the instruction to the CP. The HighWaterMark records the
179 /// highest basic block where a new CPEntry can be placed. To ensure this
180 /// pass terminates, the CP entries are initially placed at the end of the
181 /// function and then move monotonically to lower addresses. The
182 /// exception to this rule is when the current CP entry for a particular
183 /// CPUser is out of range, but there is another CP entry for the same
184 /// constant value in range. We want to use the existing in-range CP
185 /// entry, but if it later moves out of range, the search for new water
186 /// should resume where it left off. The HighWaterMark is used to record
191 MachineBasicBlock *HighWaterMark;
195 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
196 bool neg, bool soimm)
197 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
198 HighWaterMark = CPEMI->getParent();
202 /// CPUsers - Keep track of all of the machine instructions that use various
203 /// constant pools and their max displacement.
204 std::vector<CPUser> CPUsers;
206 /// CPEntry - One per constant pool entry, keeping the machine instruction
207 /// pointer, the constpool index, and the number of CPUser's which
208 /// reference this entry.
213 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
214 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
217 /// CPEntries - Keep track of all of the constant pool entry machine
218 /// instructions. For each original constpool index (i.e. those that
219 /// existed upon entry to this pass), it keeps a vector of entries.
220 /// Original elements are cloned as we go along; the clones are
221 /// put in the vector of the original element, but have distinct CPIs.
222 std::vector<std::vector<CPEntry> > CPEntries;
224 /// ImmBranch - One per immediate branch, keeping the machine instruction
225 /// pointer, conditional or unconditional, the max displacement,
226 /// and (if isCond is true) the corresponding unconditional branch
230 unsigned MaxDisp : 31;
233 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
234 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
237 /// ImmBranches - Keep track of all the immediate branch instructions.
239 std::vector<ImmBranch> ImmBranches;
241 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
243 SmallVector<MachineInstr*, 4> PushPopMIs;
245 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
246 SmallVector<MachineInstr*, 4> T2JumpTables;
248 /// HasFarJump - True if any far jump instruction has been emitted during
249 /// the branch fix up pass.
253 MachineConstantPool *MCP;
254 const ARMInstrInfo *TII;
255 const ARMSubtarget *STI;
256 ARMFunctionInfo *AFI;
262 ARMConstantIslands() : MachineFunctionPass(ID) {}
264 virtual bool runOnMachineFunction(MachineFunction &MF);
266 virtual const char *getPassName() const {
267 return "ARM constant island placement and branch shortening pass";
271 void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
272 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
273 unsigned getCPELogAlign(const MachineInstr *CPEMI);
274 void JumpTableFunctionScan();
275 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
276 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
277 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
278 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
279 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
280 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
281 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
282 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
283 MachineBasicBlock *&NewMBB);
284 bool HandleConstantPoolUser(unsigned CPUserIndex);
285 void RemoveDeadCPEMI(MachineInstr *CPEMI);
286 bool RemoveUnusedCPEntries();
287 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
288 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
289 bool DoDump = false);
290 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
292 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
293 bool FixUpImmediateBr(ImmBranch &Br);
294 bool FixUpConditionalBr(ImmBranch &Br);
295 bool FixUpUnconditionalBr(ImmBranch &Br);
296 bool UndoLRSpillRestore();
297 bool OptimizeThumb2Instructions();
298 bool OptimizeThumb2Branches();
299 bool ReorderThumb2JumpTables();
300 bool OptimizeThumb2JumpTables();
301 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
302 MachineBasicBlock *JTBB);
304 void ComputeBlockSize(MachineBasicBlock *MBB);
305 unsigned GetOffsetOf(MachineInstr *MI) const;
309 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
310 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
311 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
313 return OffsetIsInRange(UserOffset, TrialOffset,
314 U.MaxDisp, U.NegOk, U.IsSoImm);
317 char ARMConstantIslands::ID = 0;
320 /// verify - check BBOffsets, BBSizes, alignment of islands
321 void ARMConstantIslands::verify() {
323 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
325 MachineBasicBlock *MBB = MBBI;
326 unsigned Align = MBB->getAlignment();
327 unsigned MBBId = MBB->getNumber();
328 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
329 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
331 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
332 CPUser &U = CPUsers[i];
333 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
334 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
335 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
336 UserOffset - CPEOffset;
337 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
342 /// print block size and offset information - debugging
343 void ARMConstantIslands::dumpBBs() {
345 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
346 const BasicBlockInfo &BBI = BBInfo[J];
347 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
348 << " kb=" << unsigned(BBI.KnownBits)
349 << " ua=" << unsigned(BBI.Unalign)
350 << " pa=" << unsigned(BBI.PostAlign)
351 << format(" size=%#x\n", BBInfo[J].Size);
356 /// createARMConstantIslandPass - returns an instance of the constpool
358 FunctionPass *llvm::createARMConstantIslandPass() {
359 return new ARMConstantIslands();
362 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
364 MCP = mf.getConstantPool();
366 DEBUG(dbgs() << "***** ARMConstantIslands: "
367 << MCP->getConstants().size() << " CP entries, aligned to "
368 << MCP->getConstantPoolAlignment() << " bytes *****\n");
370 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
371 AFI = MF->getInfo<ARMFunctionInfo>();
372 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
374 isThumb = AFI->isThumbFunction();
375 isThumb1 = AFI->isThumb1OnlyFunction();
376 isThumb2 = AFI->isThumb2Function();
380 // Renumber all of the machine basic blocks in the function, guaranteeing that
381 // the numbers agree with the position of the block in the function.
382 MF->RenumberBlocks();
384 // Try to reorder and otherwise adjust the block layout to make good use
385 // of the TB[BH] instructions.
386 bool MadeChange = false;
387 if (isThumb2 && AdjustJumpTableBlocks) {
388 JumpTableFunctionScan();
389 MadeChange |= ReorderThumb2JumpTables();
390 // Data is out of date, so clear it. It'll be re-computed later.
391 T2JumpTables.clear();
392 // Blocks may have shifted around. Keep the numbering up to date.
393 MF->RenumberBlocks();
396 // Thumb1 functions containing constant pools get 4-byte alignment.
397 // This is so we can keep exact track of where the alignment padding goes.
399 // ARM and Thumb2 functions need to be 4-byte aligned.
401 MF->EnsureAlignment(2); // 2 = log2(4)
403 // Perform the initial placement of the constant pool entries. To start with,
404 // we put them all at the end of the function.
405 std::vector<MachineInstr*> CPEMIs;
407 DoInitialPlacement(CPEMIs);
409 /// The next UID to take is the first unused one.
410 AFI->initPICLabelUId(CPEMIs.size());
412 // Do the initial scan of the function, building up information about the
413 // sizes of each block, the location of all the water, and finding all of the
414 // constant pool users.
415 InitialFunctionScan(CPEMIs);
420 /// Remove dead constant pool entries.
421 MadeChange |= RemoveUnusedCPEntries();
423 // Iteratively place constant pool entries and fix up branches until there
425 unsigned NoCPIters = 0, NoBRIters = 0;
427 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
428 bool CPChange = false;
429 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
430 CPChange |= HandleConstantPoolUser(i);
431 if (CPChange && ++NoCPIters > 30)
432 llvm_unreachable("Constant Island pass failed to converge!");
435 // Clear NewWaterList now. If we split a block for branches, it should
436 // appear as "new water" for the next iteration of constant pool placement.
437 NewWaterList.clear();
439 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
440 bool BRChange = false;
441 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
442 BRChange |= FixUpImmediateBr(ImmBranches[i]);
443 if (BRChange && ++NoBRIters > 30)
444 llvm_unreachable("Branch Fix Up pass failed to converge!");
447 if (!CPChange && !BRChange)
452 // Shrink 32-bit Thumb2 branch, load, and store instructions.
453 if (isThumb2 && !STI->prefers32BitThumb())
454 MadeChange |= OptimizeThumb2Instructions();
456 // After a while, this might be made debug-only, but it is not expensive.
459 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
460 // undo the spill / restore of LR if possible.
461 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
462 MadeChange |= UndoLRSpillRestore();
464 // Save the mapping between original and cloned constpool entries.
465 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
466 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
467 const CPEntry & CPE = CPEntries[i][j];
468 AFI->recordCPEClone(i, CPE.CPI);
472 DEBUG(dbgs() << '\n'; dumpBBs());
480 T2JumpTables.clear();
485 /// DoInitialPlacement - Perform the initial placement of the constant pool
486 /// entries. To start with, we put them all at the end of the function.
488 ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
489 // Create the basic block to hold the CPE's.
490 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
493 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
494 unsigned MaxAlign = Log2_32(MF->getConstantPool()->getConstantPoolAlignment());
496 // Mark the basic block as required by the const-pool.
497 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
498 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
500 // The function needs to be as aligned as the basic blocks. The linker may
501 // move functions around based on their alignment.
502 MF->EnsureAlignment(BB->getAlignment());
504 // Order the entries in BB by descending alignment. That ensures correct
505 // alignment of all entries as long as BB is sufficiently aligned. Keep
506 // track of the insertion point for each alignment. We are going to bucket
507 // sort the entries as they are created.
508 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
510 // Add all of the constants from the constant pool to the end block, use an
511 // identity mapping of CPI's to CPE's.
512 const std::vector<MachineConstantPoolEntry> &CPs =
513 MF->getConstantPool()->getConstants();
515 const TargetData &TD = *MF->getTarget().getTargetData();
516 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
517 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
518 assert(Size >= 4 && "Too small constant pool entry");
519 unsigned Align = CPs[i].getAlignment();
520 assert(isPowerOf2_32(Align) && "Invalid alignment");
521 // Verify that all constant pool entries are a multiple of their alignment.
522 // If not, we would have to pad them out so that instructions stay aligned.
523 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
525 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
526 unsigned LogAlign = Log2_32(Align);
527 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
528 MachineInstr *CPEMI =
529 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
530 .addImm(i).addConstantPoolIndex(i).addImm(Size);
531 CPEMIs.push_back(CPEMI);
533 // Ensure that future entries with higher alignment get inserted before
534 // CPEMI. This is bucket sort with iterators.
535 for (unsigned a = LogAlign + 1; a < MaxAlign; ++a)
536 if (InsPoint[a] == InsAt)
539 // Add a new CPEntry, but no corresponding CPUser yet.
540 std::vector<CPEntry> CPEs;
541 CPEs.push_back(CPEntry(CPEMI, i));
542 CPEntries.push_back(CPEs);
544 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
549 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
550 /// into the block immediately after it.
551 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
552 // Get the next machine basic block in the function.
553 MachineFunction::iterator MBBI = MBB;
554 // Can't fall off end of function.
555 if (llvm::next(MBBI) == MBB->getParent()->end())
558 MachineBasicBlock *NextBB = llvm::next(MBBI);
559 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
560 E = MBB->succ_end(); I != E; ++I)
567 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
568 /// look up the corresponding CPEntry.
569 ARMConstantIslands::CPEntry
570 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
571 const MachineInstr *CPEMI) {
572 std::vector<CPEntry> &CPEs = CPEntries[CPI];
573 // Number of entries per constpool index should be small, just do a
575 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
576 if (CPEs[i].CPEMI == CPEMI)
582 /// getCPELogAlign - Returns the required alignment of the constant pool entry
583 /// represented by CPEMI. ALignment is measured in log2(bytes) units.
584 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
585 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
587 // Everything is 4-byte aligned unless AlignConstantIslands is set.
588 if (!AlignConstantIslands)
591 unsigned CPI = CPEMI->getOperand(1).getIndex();
592 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
593 unsigned Align = MCP->getConstants()[CPI].getAlignment();
594 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
595 return Log2_32(Align);
598 /// JumpTableFunctionScan - Do a scan of the function, building up
599 /// information about the sizes of each block and the locations of all
601 void ARMConstantIslands::JumpTableFunctionScan() {
602 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
604 MachineBasicBlock &MBB = *MBBI;
606 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
608 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
609 T2JumpTables.push_back(I);
613 /// InitialFunctionScan - Do the initial scan of the function, building up
614 /// information about the sizes of each block, the location of all the water,
615 /// and finding all of the constant pool users.
616 void ARMConstantIslands::
617 InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
619 BBInfo.resize(MF->getNumBlockIDs());
621 // First thing, compute the size of all basic blocks, and see if the function
622 // has any inline assembly in it. If so, we have to be conservative about
623 // alignment assumptions, as we don't know for sure the size of any
624 // instructions in the inline assembly.
625 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
628 // The known bits of the entry block offset are determined by the function
630 BBInfo.front().KnownBits = MF->getAlignment();
632 // Compute block offsets and known bits.
633 AdjustBBOffsetsAfter(MF->begin());
635 // Now go back through the instructions and build up our data structures.
636 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
638 MachineBasicBlock &MBB = *MBBI;
640 // If this block doesn't fall through into the next MBB, then this is
641 // 'water' that a constant pool island could be placed.
642 if (!BBHasFallthrough(&MBB))
643 WaterList.push_back(&MBB);
645 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
647 if (I->isDebugValue())
650 int Opc = I->getOpcode();
658 continue; // Ignore other JT branches
660 T2JumpTables.push_back(I);
661 continue; // Does not get an entry in ImmBranches
692 // Record this immediate branch.
693 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
694 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
697 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
698 PushPopMIs.push_back(I);
700 if (Opc == ARM::CONSTPOOL_ENTRY)
703 // Scan the instructions for constant pool operands.
704 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
705 if (I->getOperand(op).isCPI()) {
706 // We found one. The addressing mode tells us the max displacement
707 // from the PC that this instruction permits.
709 // Basic size info comes from the TSFlags field.
713 bool IsSoImm = false;
717 llvm_unreachable("Unknown addressing mode for CP reference!");
720 // Taking the address of a CP entry.
722 // This takes a SoImm, which is 8 bit immediate rotated. We'll
723 // pretend the maximum offset is 255 * 4. Since each instruction
724 // 4 byte wide, this is always correct. We'll check for other
725 // displacements that fits in a SoImm as well.
731 case ARM::t2LEApcrel:
743 Bits = 12; // +-offset_12
749 Scale = 4; // +(offset_8*4)
755 Scale = 4; // +-(offset_8*4)
760 // Remember that this is a user of a CP entry.
761 unsigned CPI = I->getOperand(op).getIndex();
762 MachineInstr *CPEMI = CPEMIs[CPI];
763 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
764 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
766 // Increment corresponding CPEntry reference count.
767 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
768 assert(CPE && "Cannot find a corresponding CPEntry!");
771 // Instructions can only use one CP entry, don't bother scanning the
772 // rest of the operands.
779 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
780 /// This function updates BBInfo directly.
781 void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
782 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
787 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
789 BBI.Size += TII->GetInstSizeInBytes(I);
790 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
791 // The actual size may be smaller, but still a multiple of the instr size.
792 if (I->isInlineAsm())
793 BBI.Unalign = isThumb ? 1 : 2;
796 // tBR_JTr contains a .align 2 directive.
797 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
799 MBB->getParent()->EnsureAlignment(2);
803 /// GetOffsetOf - Return the current offset of the specified machine instruction
804 /// from the start of the function. This offset changes as stuff is moved
805 /// around inside the function.
806 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
807 MachineBasicBlock *MBB = MI->getParent();
809 // The offset is composed of two things: the sum of the sizes of all MBB's
810 // before this instruction's block, and the offset from the start of the block
812 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
814 // Sum instructions before MI in MBB.
815 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
816 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
817 if (&*I == MI) return Offset;
818 Offset += TII->GetInstSizeInBytes(I);
822 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
824 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
825 const MachineBasicBlock *RHS) {
826 return LHS->getNumber() < RHS->getNumber();
829 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
830 /// machine function, it upsets all of the block numbers. Renumber the blocks
831 /// and update the arrays that parallel this numbering.
832 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
833 // Renumber the MBB's to keep them consecutive.
834 NewBB->getParent()->RenumberBlocks(NewBB);
836 // Insert an entry into BBInfo to align it properly with the (newly
837 // renumbered) block numbers.
838 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
840 // Next, update WaterList. Specifically, we need to add NewMBB as having
841 // available water after it.
843 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
845 WaterList.insert(IP, NewBB);
849 /// Split the basic block containing MI into two blocks, which are joined by
850 /// an unconditional branch. Update data structures and renumber blocks to
851 /// account for this change and returns the newly created block.
852 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
853 MachineBasicBlock *OrigBB = MI->getParent();
855 // Create a new MBB for the code after the OrigBB.
856 MachineBasicBlock *NewBB =
857 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
858 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
859 MF->insert(MBBI, NewBB);
861 // Splice the instructions starting with MI over to NewBB.
862 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
864 // Add an unconditional branch from OrigBB to NewBB.
865 // Note the new unconditional branch is not being recorded.
866 // There doesn't seem to be meaningful DebugInfo available; this doesn't
867 // correspond to anything in the source.
868 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
870 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
872 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
873 .addImm(ARMCC::AL).addReg(0);
876 // Update the CFG. All succs of OrigBB are now succs of NewBB.
877 NewBB->transferSuccessors(OrigBB);
879 // OrigBB branches to NewBB.
880 OrigBB->addSuccessor(NewBB);
882 // Update internal data structures to account for the newly inserted MBB.
883 // This is almost the same as UpdateForInsertedWaterBlock, except that
884 // the Water goes after OrigBB, not NewBB.
885 MF->RenumberBlocks(NewBB);
887 // Insert an entry into BBInfo to align it properly with the (newly
888 // renumbered) block numbers.
889 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
891 // Next, update WaterList. Specifically, we need to add OrigMBB as having
892 // available water after it (but not if it's already there, which happens
893 // when splitting before a conditional branch that is followed by an
894 // unconditional branch - in that case we want to insert NewBB).
896 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
898 MachineBasicBlock* WaterBB = *IP;
899 if (WaterBB == OrigBB)
900 WaterList.insert(llvm::next(IP), NewBB);
902 WaterList.insert(IP, OrigBB);
903 NewWaterList.insert(OrigBB);
905 // Figure out how large the OrigBB is. As the first half of the original
906 // block, it cannot contain a tablejump. The size includes
907 // the new jump we added. (It should be possible to do this without
908 // recounting everything, but it's very confusing, and this is rarely
910 ComputeBlockSize(OrigBB);
912 // Figure out how large the NewMBB is. As the second half of the original
913 // block, it may contain a tablejump.
914 ComputeBlockSize(NewBB);
916 // All BBOffsets following these blocks must be modified.
917 AdjustBBOffsetsAfter(OrigBB);
922 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
923 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
924 /// constant pool entry).
925 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
926 unsigned TrialOffset, unsigned MaxDisp,
927 bool NegativeOK, bool IsSoImm) {
928 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
929 // purposes of the displacement computation; compensate for that here.
930 // Effectively, the valid range of displacements is 2 bytes smaller for such
932 unsigned TotalAdj = 0;
933 if (isThumb && UserOffset%4 !=0) {
937 // CPEs will be rounded up to a multiple of 4.
938 if (isThumb && TrialOffset%4 != 0) {
943 // In Thumb2 mode, later branch adjustments can shift instructions up and
944 // cause alignment change. In the worst case scenario this can cause the
945 // user's effective address to be subtracted by 2 and the CPE's address to
947 if (isThumb2 && TotalAdj != 4)
948 MaxDisp -= (4 - TotalAdj);
950 if (UserOffset <= TrialOffset) {
951 // User before the Trial.
952 if (TrialOffset - UserOffset <= MaxDisp)
954 // FIXME: Make use full range of soimm values.
955 } else if (NegativeOK) {
956 if (UserOffset - TrialOffset <= MaxDisp)
958 // FIXME: Make use full range of soimm values.
963 /// WaterIsInRange - Returns true if a CPE placed after the specified
964 /// Water (a basic block) will be in range for the specific MI.
966 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
967 MachineBasicBlock* Water, CPUser &U) {
968 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
970 // If the CPE is to be inserted before the instruction, that will raise
971 // the offset of the instruction.
972 if (CPEOffset < UserOffset)
973 UserOffset += U.CPEMI->getOperand(2).getImm();
975 return OffsetIsInRange(UserOffset, CPEOffset, U);
978 /// CPEIsInRange - Returns true if the distance between specific MI and
979 /// specific ConstPool entry instruction can fit in MI's displacement field.
980 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
981 MachineInstr *CPEMI, unsigned MaxDisp,
982 bool NegOk, bool DoDump) {
983 unsigned CPEOffset = GetOffsetOf(CPEMI);
984 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
988 unsigned Block = MI->getParent()->getNumber();
989 const BasicBlockInfo &BBI = BBInfo[Block];
990 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
991 << " max delta=" << MaxDisp
992 << format(" insn address=%#x", UserOffset)
993 << " in BB#" << Block << ": "
994 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
995 << format("CPE address=%#x offset=%+d: ", CPEOffset,
996 int(CPEOffset-UserOffset));
1000 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1004 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1005 /// unconditionally branches to its only successor.
1006 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1007 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1010 MachineBasicBlock *Succ = *MBB->succ_begin();
1011 MachineBasicBlock *Pred = *MBB->pred_begin();
1012 MachineInstr *PredMI = &Pred->back();
1013 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1014 || PredMI->getOpcode() == ARM::t2B)
1015 return PredMI->getOperand(0).getMBB() == Succ;
1020 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
1021 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1022 // Get the offset and known bits at the end of the layout predecessor.
1023 unsigned Offset = BBInfo[i - 1].postOffset();
1024 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
1026 // Add padding before an aligned block. This may teach us more bits.
1027 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
1028 Offset = WorstCaseAlign(Offset, Align, KnownBits);
1029 KnownBits = std::max(KnownBits, Align);
1032 // This is where block i begins.
1033 BBInfo[i].Offset = Offset;
1034 BBInfo[i].KnownBits = KnownBits;
1038 /// DecrementOldEntry - find the constant pool entry with index CPI
1039 /// and instruction CPEMI, and decrement its refcount. If the refcount
1040 /// becomes 0 remove the entry and instruction. Returns true if we removed
1041 /// the entry, false if we didn't.
1043 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
1044 // Find the old entry. Eliminate it if it is no longer used.
1045 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1046 assert(CPE && "Unexpected!");
1047 if (--CPE->RefCount == 0) {
1048 RemoveDeadCPEMI(CPEMI);
1056 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1057 /// if not, see if an in-range clone of the CPE is in range, and if so,
1058 /// change the data structures so the user references the clone. Returns:
1059 /// 0 = no existing entry found
1060 /// 1 = entry found, and there were no code insertions or deletions
1061 /// 2 = entry found, and there were code insertions or deletions
1062 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1064 MachineInstr *UserMI = U.MI;
1065 MachineInstr *CPEMI = U.CPEMI;
1067 // Check to see if the CPE is already in-range.
1068 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1069 DEBUG(dbgs() << "In range\n");
1073 // No. Look for previously created clones of the CPE that are in range.
1074 unsigned CPI = CPEMI->getOperand(1).getIndex();
1075 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1076 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1077 // We already tried this one
1078 if (CPEs[i].CPEMI == CPEMI)
1080 // Removing CPEs can leave empty entries, skip
1081 if (CPEs[i].CPEMI == NULL)
1083 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1084 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1085 << CPEs[i].CPI << "\n");
1086 // Point the CPUser node to the replacement
1087 U.CPEMI = CPEs[i].CPEMI;
1088 // Change the CPI in the instruction operand to refer to the clone.
1089 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1090 if (UserMI->getOperand(j).isCPI()) {
1091 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1094 // Adjust the refcount of the clone...
1096 // ...and the original. If we didn't remove the old entry, none of the
1097 // addresses changed, so we don't need another pass.
1098 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1104 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1105 /// the specific unconditional branch instruction.
1106 static inline unsigned getUnconditionalBrDisp(int Opc) {
1109 return ((1<<10)-1)*2;
1111 return ((1<<23)-1)*2;
1116 return ((1<<23)-1)*4;
1119 /// LookForWater - Look for an existing entry in the WaterList in which
1120 /// we can place the CPE referenced from U so it's within range of U's MI.
1121 /// Returns true if found, false if not. If it returns true, WaterIter
1122 /// is set to the WaterList entry. For Thumb, prefer water that will not
1123 /// introduce padding to water that will. To ensure that this pass
1124 /// terminates, the CPE location for a particular CPUser is only allowed to
1125 /// move to a lower address, so search backward from the end of the list and
1126 /// prefer the first water that is in range.
1127 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1128 water_iterator &WaterIter) {
1129 if (WaterList.empty())
1132 bool FoundWaterThatWouldPad = false;
1133 water_iterator IPThatWouldPad;
1134 for (water_iterator IP = prior(WaterList.end()),
1135 B = WaterList.begin();; --IP) {
1136 MachineBasicBlock* WaterBB = *IP;
1137 // Check if water is in range and is either at a lower address than the
1138 // current "high water mark" or a new water block that was created since
1139 // the previous iteration by inserting an unconditional branch. In the
1140 // latter case, we want to allow resetting the high water mark back to
1141 // this new water since we haven't seen it before. Inserting branches
1142 // should be relatively uncommon and when it does happen, we want to be
1143 // sure to take advantage of it for all the CPEs near that block, so that
1144 // we don't insert more branches than necessary.
1145 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1146 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1147 NewWaterList.count(WaterBB))) {
1148 unsigned WBBId = WaterBB->getNumber();
1149 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1150 // This is valid Water, but would introduce padding. Remember
1151 // it in case we don't find any Water that doesn't do this.
1152 if (!FoundWaterThatWouldPad) {
1153 FoundWaterThatWouldPad = true;
1154 IPThatWouldPad = IP;
1164 if (FoundWaterThatWouldPad) {
1165 WaterIter = IPThatWouldPad;
1171 /// CreateNewWater - No existing WaterList entry will work for
1172 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1173 /// block is used if in range, and the conditional branch munged so control
1174 /// flow is correct. Otherwise the block is split to create a hole with an
1175 /// unconditional branch around it. In either case NewMBB is set to a
1176 /// block following which the new island can be inserted (the WaterList
1177 /// is not adjusted).
1178 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1179 unsigned UserOffset,
1180 MachineBasicBlock *&NewMBB) {
1181 CPUser &U = CPUsers[CPUserIndex];
1182 MachineInstr *UserMI = U.MI;
1183 MachineInstr *CPEMI = U.CPEMI;
1184 MachineBasicBlock *UserMBB = UserMI->getParent();
1185 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1186 unsigned OffsetOfNextBlock = UserBBI.postOffset();
1188 // If the block does not end in an unconditional branch already, and if the
1189 // end of the block is within range, make new water there. (The addition
1190 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1191 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1192 // inside OffsetIsInRange.
1193 if (BBHasFallthrough(UserMBB) &&
1194 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
1195 DEBUG(dbgs() << "Split at end of block\n");
1196 if (&UserMBB->back() == UserMI)
1197 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1198 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1199 // Add an unconditional branch from UserMBB to fallthrough block.
1200 // Record it for branch lengthening; this new branch will not get out of
1201 // range, but if the preceding conditional branch is out of range, the
1202 // targets will be exchanged, and the altered branch may be out of
1203 // range, so the machinery has to know about it.
1204 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1206 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1208 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1209 .addImm(ARMCC::AL).addReg(0);
1210 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1211 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1212 MaxDisp, false, UncondBr));
1213 int delta = isThumb1 ? 2 : 4;
1214 BBInfo[UserMBB->getNumber()].Size += delta;
1215 AdjustBBOffsetsAfter(UserMBB);
1217 // What a big block. Find a place within the block to split it.
1218 // This is a little tricky on Thumb1 since instructions are 2 bytes
1219 // and constant pool entries are 4 bytes: if instruction I references
1220 // island CPE, and instruction I+1 references CPE', it will
1221 // not work well to put CPE as far forward as possible, since then
1222 // CPE' cannot immediately follow it (that location is 2 bytes
1223 // farther away from I+1 than CPE was from I) and we'd need to create
1224 // a new island. So, we make a first guess, then walk through the
1225 // instructions between the one currently being looked at and the
1226 // possible insertion point, and make sure any other instructions
1227 // that reference CPEs will be able to use the same island area;
1228 // if not, we back up the insertion point.
1230 // Try to split the block so it's fully aligned. Compute the latest split
1231 // point where we can add a 4-byte branch instruction, and then
1232 // WorstCaseAlign to LogAlign.
1233 unsigned LogAlign = UserMBB->getParent()->getAlignment();
1234 unsigned KnownBits = UserBBI.internalKnownBits();
1235 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1236 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1237 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1240 // Account for alignment and unknown padding.
1241 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1242 BaseInsertOffset -= UPad;
1244 // The 4 in the following is for the unconditional branch we'll be
1245 // inserting (allows for long branch on Thumb1). Alignment of the
1246 // island is handled inside OffsetIsInRange.
1247 BaseInsertOffset -= 4;
1249 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1250 << " la=" << LogAlign
1251 << " kb=" << KnownBits
1252 << " up=" << UPad << '\n');
1254 // This could point off the end of the block if we've already got
1255 // constant pool entries following this block; only the last one is
1256 // in the water list. Back past any possible branches (allow for a
1257 // conditional and a maximally long unconditional).
1258 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1259 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1261 unsigned EndInsertOffset =
1262 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1263 CPEMI->getOperand(2).getImm();
1264 MachineBasicBlock::iterator MI = UserMI;
1266 unsigned CPUIndex = CPUserIndex+1;
1267 unsigned NumCPUsers = CPUsers.size();
1268 MachineInstr *LastIT = 0;
1269 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1270 Offset < BaseInsertOffset;
1271 Offset += TII->GetInstSizeInBytes(MI),
1272 MI = llvm::next(MI)) {
1273 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1274 CPUser &U = CPUsers[CPUIndex];
1275 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
1276 BaseInsertOffset -= 1u << LogAlign;
1277 EndInsertOffset -= 1u << LogAlign;
1279 // This is overly conservative, as we don't account for CPEMIs
1280 // being reused within the block, but it doesn't matter much.
1281 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1285 // Remember the last IT instruction.
1286 if (MI->getOpcode() == ARM::t2IT)
1292 // Avoid splitting an IT block.
1294 unsigned PredReg = 0;
1295 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1296 if (CC != ARMCC::AL)
1299 NewMBB = SplitBlockBeforeInstr(MI);
1303 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1304 /// is out-of-range. If so, pick up the constant pool value and move it some
1305 /// place in-range. Return true if we changed any addresses (thus must run
1306 /// another pass of branch lengthening), false otherwise.
1307 bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
1308 CPUser &U = CPUsers[CPUserIndex];
1309 MachineInstr *UserMI = U.MI;
1310 MachineInstr *CPEMI = U.CPEMI;
1311 unsigned CPI = CPEMI->getOperand(1).getIndex();
1312 unsigned Size = CPEMI->getOperand(2).getImm();
1313 // Compute this only once, it's expensive. The 4 or 8 is the value the
1314 // hardware keeps in the PC.
1315 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1317 // See if the current entry is within range, or there is a clone of it
1319 int result = LookForExistingCPEntry(U, UserOffset);
1320 if (result==1) return false;
1321 else if (result==2) return true;
1323 // No existing clone of this CPE is within range.
1324 // We will be generating a new clone. Get a UID for it.
1325 unsigned ID = AFI->createPICLabelUId();
1327 // Look for water where we can place this CPE.
1328 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1329 MachineBasicBlock *NewMBB;
1331 if (LookForWater(U, UserOffset, IP)) {
1332 DEBUG(dbgs() << "Found water in range\n");
1333 MachineBasicBlock *WaterBB = *IP;
1335 // If the original WaterList entry was "new water" on this iteration,
1336 // propagate that to the new island. This is just keeping NewWaterList
1337 // updated to match the WaterList, which will be updated below.
1338 if (NewWaterList.count(WaterBB)) {
1339 NewWaterList.erase(WaterBB);
1340 NewWaterList.insert(NewIsland);
1342 // The new CPE goes before the following block (NewMBB).
1343 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1347 DEBUG(dbgs() << "No water found\n");
1348 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1350 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1351 // called while handling branches so that the water will be seen on the
1352 // next iteration for constant pools, but in this context, we don't want
1353 // it. Check for this so it will be removed from the WaterList.
1354 // Also remove any entry from NewWaterList.
1355 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1356 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1357 if (IP != WaterList.end())
1358 NewWaterList.erase(WaterBB);
1360 // We are adding new water. Update NewWaterList.
1361 NewWaterList.insert(NewIsland);
1364 // Remove the original WaterList entry; we want subsequent insertions in
1365 // this vicinity to go after the one we're about to insert. This
1366 // considerably reduces the number of times we have to move the same CPE
1367 // more than once and is also important to ensure the algorithm terminates.
1368 if (IP != WaterList.end())
1369 WaterList.erase(IP);
1371 // Okay, we know we can put an island before NewMBB now, do it!
1372 MF->insert(NewMBB, NewIsland);
1374 // Update internal data structures to account for the newly inserted MBB.
1375 UpdateForInsertedWaterBlock(NewIsland);
1377 // Decrement the old entry, and remove it if refcount becomes 0.
1378 DecrementOldEntry(CPI, CPEMI);
1380 // Now that we have an island to add the CPE to, clone the original CPE and
1381 // add it to the island.
1382 U.HighWaterMark = NewIsland;
1383 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1384 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1385 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1388 // Mark the basic block as aligned as required by the const-pool entry.
1389 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1391 // Increase the size of the island block to account for the new entry.
1392 BBInfo[NewIsland->getNumber()].Size += Size;
1393 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1395 // Finally, change the CPI in the instruction operand to be ID.
1396 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1397 if (UserMI->getOperand(i).isCPI()) {
1398 UserMI->getOperand(i).setIndex(ID);
1402 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1403 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1408 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1409 /// sizes and offsets of impacted basic blocks.
1410 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1411 MachineBasicBlock *CPEBB = CPEMI->getParent();
1412 unsigned Size = CPEMI->getOperand(2).getImm();
1413 CPEMI->eraseFromParent();
1414 BBInfo[CPEBB->getNumber()].Size -= Size;
1415 // All succeeding offsets have the current size value added in, fix this.
1416 if (CPEBB->empty()) {
1417 BBInfo[CPEBB->getNumber()].Size = 0;
1419 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1420 CPEBB->setAlignment(0);
1422 // Entries are sorted by descending alignment, so realign from the front.
1423 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1425 AdjustBBOffsetsAfter(CPEBB);
1426 // An island has only one predecessor BB and one successor BB. Check if
1427 // this BB's predecessor jumps directly to this BB's successor. This
1428 // shouldn't happen currently.
1429 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1430 // FIXME: remove the empty blocks after all the work is done?
1433 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1435 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1436 unsigned MadeChange = false;
1437 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1438 std::vector<CPEntry> &CPEs = CPEntries[i];
1439 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1440 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1441 RemoveDeadCPEMI(CPEs[j].CPEMI);
1442 CPEs[j].CPEMI = NULL;
1450 /// BBIsInRange - Returns true if the distance between specific MI and
1451 /// specific BB can fit in MI's displacement field.
1452 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1454 unsigned PCAdj = isThumb ? 4 : 8;
1455 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1456 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1458 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1459 << " from BB#" << MI->getParent()->getNumber()
1460 << " max delta=" << MaxDisp
1461 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1462 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1464 if (BrOffset <= DestOffset) {
1465 // Branch before the Dest.
1466 if (DestOffset-BrOffset <= MaxDisp)
1469 if (BrOffset-DestOffset <= MaxDisp)
1475 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1476 /// away to fit in its displacement field.
1477 bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
1478 MachineInstr *MI = Br.MI;
1479 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1481 // Check to see if the DestBB is already in-range.
1482 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1486 return FixUpUnconditionalBr(Br);
1487 return FixUpConditionalBr(Br);
1490 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1491 /// too far away to fit in its displacement field. If the LR register has been
1492 /// spilled in the epilogue, then we can use BL to implement a far jump.
1493 /// Otherwise, add an intermediate branch instruction to a branch.
1495 ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
1496 MachineInstr *MI = Br.MI;
1497 MachineBasicBlock *MBB = MI->getParent();
1499 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1501 // Use BL to implement far jump.
1502 Br.MaxDisp = (1 << 21) * 2;
1503 MI->setDesc(TII->get(ARM::tBfar));
1504 BBInfo[MBB->getNumber()].Size += 2;
1505 AdjustBBOffsetsAfter(MBB);
1509 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1514 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1515 /// far away to fit in its displacement field. It is converted to an inverse
1516 /// conditional branch + an unconditional branch to the destination.
1518 ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
1519 MachineInstr *MI = Br.MI;
1520 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1522 // Add an unconditional branch to the destination and invert the branch
1523 // condition to jump over it:
1529 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1530 CC = ARMCC::getOppositeCondition(CC);
1531 unsigned CCReg = MI->getOperand(2).getReg();
1533 // If the branch is at the end of its MBB and that has a fall-through block,
1534 // direct the updated conditional branch to the fall-through block. Otherwise,
1535 // split the MBB before the next instruction.
1536 MachineBasicBlock *MBB = MI->getParent();
1537 MachineInstr *BMI = &MBB->back();
1538 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1542 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1543 BMI->getOpcode() == Br.UncondBr) {
1544 // Last MI in the BB is an unconditional branch. Can we simply invert the
1545 // condition and swap destinations:
1551 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1552 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1553 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1555 BMI->getOperand(0).setMBB(DestBB);
1556 MI->getOperand(0).setMBB(NewDest);
1557 MI->getOperand(1).setImm(CC);
1564 SplitBlockBeforeInstr(MI);
1565 // No need for the branch to the next block. We're adding an unconditional
1566 // branch to the destination.
1567 int delta = TII->GetInstSizeInBytes(&MBB->back());
1568 BBInfo[MBB->getNumber()].Size -= delta;
1569 MBB->back().eraseFromParent();
1570 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1572 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1574 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1575 << " also invert condition and change dest. to BB#"
1576 << NextBB->getNumber() << "\n");
1578 // Insert a new conditional branch and a new unconditional branch.
1579 // Also update the ImmBranch as well as adding a new entry for the new branch.
1580 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1581 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1582 Br.MI = &MBB->back();
1583 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1585 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1586 .addImm(ARMCC::AL).addReg(0);
1588 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1589 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1590 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1591 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1593 // Remove the old conditional branch. It may or may not still be in MBB.
1594 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1595 MI->eraseFromParent();
1596 AdjustBBOffsetsAfter(MBB);
1600 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1601 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1602 /// to do this if tBfar is not used.
1603 bool ARMConstantIslands::UndoLRSpillRestore() {
1604 bool MadeChange = false;
1605 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1606 MachineInstr *MI = PushPopMIs[i];
1607 // First two operands are predicates.
1608 if (MI->getOpcode() == ARM::tPOP_RET &&
1609 MI->getOperand(2).getReg() == ARM::PC &&
1610 MI->getNumExplicitOperands() == 3) {
1611 // Create the new insn and copy the predicate from the old.
1612 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1613 .addOperand(MI->getOperand(0))
1614 .addOperand(MI->getOperand(1));
1615 MI->eraseFromParent();
1622 bool ARMConstantIslands::OptimizeThumb2Instructions() {
1623 bool MadeChange = false;
1625 // Shrink ADR and LDR from constantpool.
1626 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1627 CPUser &U = CPUsers[i];
1628 unsigned Opcode = U.MI->getOpcode();
1629 unsigned NewOpc = 0;
1634 case ARM::t2LEApcrel:
1635 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1636 NewOpc = ARM::tLEApcrel;
1642 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1643 NewOpc = ARM::tLDRpci;
1653 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1654 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1655 // FIXME: Check if offset is multiple of scale if scale is not 4.
1656 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1657 U.MI->setDesc(TII->get(NewOpc));
1658 MachineBasicBlock *MBB = U.MI->getParent();
1659 BBInfo[MBB->getNumber()].Size -= 2;
1660 AdjustBBOffsetsAfter(MBB);
1666 MadeChange |= OptimizeThumb2Branches();
1667 MadeChange |= OptimizeThumb2JumpTables();
1671 bool ARMConstantIslands::OptimizeThumb2Branches() {
1672 bool MadeChange = false;
1674 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1675 ImmBranch &Br = ImmBranches[i];
1676 unsigned Opcode = Br.MI->getOpcode();
1677 unsigned NewOpc = 0;
1695 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1696 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1697 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1698 Br.MI->setDesc(TII->get(NewOpc));
1699 MachineBasicBlock *MBB = Br.MI->getParent();
1700 BBInfo[MBB->getNumber()].Size -= 2;
1701 AdjustBBOffsetsAfter(MBB);
1707 Opcode = Br.MI->getOpcode();
1708 if (Opcode != ARM::tBcc)
1712 unsigned PredReg = 0;
1713 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1714 if (Pred == ARMCC::EQ)
1716 else if (Pred == ARMCC::NE)
1717 NewOpc = ARM::tCBNZ;
1720 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1721 // Check if the distance is within 126. Subtract starting offset by 2
1722 // because the cmp will be eliminated.
1723 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1724 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1725 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1726 MachineBasicBlock::iterator CmpMI = Br.MI;
1727 if (CmpMI != Br.MI->getParent()->begin()) {
1729 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1730 unsigned Reg = CmpMI->getOperand(0).getReg();
1731 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1732 if (Pred == ARMCC::AL &&
1733 CmpMI->getOperand(1).getImm() == 0 &&
1734 isARMLowRegister(Reg)) {
1735 MachineBasicBlock *MBB = Br.MI->getParent();
1736 MachineInstr *NewBR =
1737 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1738 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1739 CmpMI->eraseFromParent();
1740 Br.MI->eraseFromParent();
1742 BBInfo[MBB->getNumber()].Size -= 2;
1743 AdjustBBOffsetsAfter(MBB);
1755 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1756 /// jumptables when it's possible.
1757 bool ARMConstantIslands::OptimizeThumb2JumpTables() {
1758 bool MadeChange = false;
1760 // FIXME: After the tables are shrunk, can we get rid some of the
1761 // constantpool tables?
1762 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1763 if (MJTI == 0) return false;
1765 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1766 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1767 MachineInstr *MI = T2JumpTables[i];
1768 const MCInstrDesc &MCID = MI->getDesc();
1769 unsigned NumOps = MCID.getNumOperands();
1770 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1771 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1772 unsigned JTI = JTOP.getIndex();
1773 assert(JTI < JT.size());
1776 bool HalfWordOk = true;
1777 unsigned JTOffset = GetOffsetOf(MI) + 4;
1778 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1779 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1780 MachineBasicBlock *MBB = JTBBs[j];
1781 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1782 // Negative offset is not ok. FIXME: We should change BB layout to make
1783 // sure all the branches are forward.
1784 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1786 unsigned TBHLimit = ((1<<16)-1)*2;
1787 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1789 if (!ByteOk && !HalfWordOk)
1793 if (ByteOk || HalfWordOk) {
1794 MachineBasicBlock *MBB = MI->getParent();
1795 unsigned BaseReg = MI->getOperand(0).getReg();
1796 bool BaseRegKill = MI->getOperand(0).isKill();
1799 unsigned IdxReg = MI->getOperand(1).getReg();
1800 bool IdxRegKill = MI->getOperand(1).isKill();
1802 // Scan backwards to find the instruction that defines the base
1803 // register. Due to post-RA scheduling, we can't count on it
1804 // immediately preceding the branch instruction.
1805 MachineBasicBlock::iterator PrevI = MI;
1806 MachineBasicBlock::iterator B = MBB->begin();
1807 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1810 // If for some reason we didn't find it, we can't do anything, so
1811 // just skip this one.
1812 if (!PrevI->definesRegister(BaseReg))
1815 MachineInstr *AddrMI = PrevI;
1817 // Examine the instruction that calculates the jumptable entry address.
1818 // Make sure it only defines the base register and kills any uses
1819 // other than the index register.
1820 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1821 const MachineOperand &MO = AddrMI->getOperand(k);
1822 if (!MO.isReg() || !MO.getReg())
1824 if (MO.isDef() && MO.getReg() != BaseReg) {
1828 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1836 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1837 // that gave us the initial base register definition.
1838 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1841 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1842 // to delete it as well.
1843 MachineInstr *LeaMI = PrevI;
1844 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1845 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1846 LeaMI->getOperand(0).getReg() != BaseReg)
1852 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1853 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1854 .addReg(IdxReg, getKillRegState(IdxRegKill))
1855 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1856 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1857 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1858 // is 2-byte aligned. For now, asm printer will fix it up.
1859 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1860 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1861 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1862 OrigSize += TII->GetInstSizeInBytes(MI);
1864 AddrMI->eraseFromParent();
1865 LeaMI->eraseFromParent();
1866 MI->eraseFromParent();
1868 int delta = OrigSize - NewSize;
1869 BBInfo[MBB->getNumber()].Size -= delta;
1870 AdjustBBOffsetsAfter(MBB);
1880 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1881 /// jump tables always branch forwards, since that's what tbb and tbh need.
1882 bool ARMConstantIslands::ReorderThumb2JumpTables() {
1883 bool MadeChange = false;
1885 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1886 if (MJTI == 0) return false;
1888 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1889 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1890 MachineInstr *MI = T2JumpTables[i];
1891 const MCInstrDesc &MCID = MI->getDesc();
1892 unsigned NumOps = MCID.getNumOperands();
1893 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1894 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1895 unsigned JTI = JTOP.getIndex();
1896 assert(JTI < JT.size());
1898 // We prefer if target blocks for the jump table come after the jump
1899 // instruction so we can use TB[BH]. Loop through the target blocks
1900 // and try to adjust them such that that's true.
1901 int JTNumber = MI->getParent()->getNumber();
1902 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1903 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1904 MachineBasicBlock *MBB = JTBBs[j];
1905 int DTNumber = MBB->getNumber();
1907 if (DTNumber < JTNumber) {
1908 // The destination precedes the switch. Try to move the block forward
1909 // so we have a positive offset.
1910 MachineBasicBlock *NewBB =
1911 AdjustJTTargetBlockForward(MBB, MI->getParent());
1913 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1922 MachineBasicBlock *ARMConstantIslands::
1923 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1925 // If the destination block is terminated by an unconditional branch,
1926 // try to move it; otherwise, create a new block following the jump
1927 // table that branches back to the actual target. This is a very simple
1928 // heuristic. FIXME: We can definitely improve it.
1929 MachineBasicBlock *TBB = 0, *FBB = 0;
1930 SmallVector<MachineOperand, 4> Cond;
1931 SmallVector<MachineOperand, 4> CondPrior;
1932 MachineFunction::iterator BBi = BB;
1933 MachineFunction::iterator OldPrior = prior(BBi);
1935 // If the block terminator isn't analyzable, don't try to move the block
1936 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1938 // If the block ends in an unconditional branch, move it. The prior block
1939 // has to have an analyzable terminator for us to move this one. Be paranoid
1940 // and make sure we're not trying to move the entry block of the function.
1941 if (!B && Cond.empty() && BB != MF->begin() &&
1942 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1943 BB->moveAfter(JTBB);
1944 OldPrior->updateTerminator();
1945 BB->updateTerminator();
1946 // Update numbering to account for the block being moved.
1947 MF->RenumberBlocks();
1952 // Create a new MBB for the code after the jump BB.
1953 MachineBasicBlock *NewBB =
1954 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
1955 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1956 MF->insert(MBBI, NewBB);
1958 // Add an unconditional branch from NewBB to BB.
1959 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1960 // correspond directly to anything in the source.
1961 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1962 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1963 .addImm(ARMCC::AL).addReg(0);
1965 // Update internal data structures to account for the newly inserted MBB.
1966 MF->RenumberBlocks(NewBB);
1969 NewBB->addSuccessor(BB);
1970 JTBB->removeSuccessor(BB);
1971 JTBB->addSuccessor(NewBB);