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/raw_ostream.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.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");
45 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
46 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
47 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
51 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
55 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
56 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
58 /// constant pool; instead, it places constants wherever it feels like with
59 /// special instructions.
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
66 class ARMConstantIslands : public MachineFunctionPass {
67 /// BasicBlockInfo - Information about the offset and size of a single
69 struct BasicBlockInfo {
70 /// Offset - Distance from the beginning of the function to the beginning
71 /// of this basic block.
73 /// The two-byte pads required for Thumb alignment are counted as part of
74 /// the following block.
77 /// Size - Size of the basic block in bytes. If the block contains
78 /// inline assembly, this is a worst case estimate.
80 /// The two-byte pads required for Thumb alignment are counted as part of
81 /// the following block (i.e., the offset and size for a padded block
82 /// will both be ==2 mod 4).
85 /// Unalign - When non-zero, the block contains instructions (inline asm)
86 /// of unknown size. The real size may be smaller than Size bytes by a
87 /// multiple of 1 << Unalign.
90 /// PostAlign - When non-zero, the block terminator contains a .align
91 /// directive, so the end of the block is aligned to 1 << PostAlign
95 BasicBlockInfo() : Offset(0), Size(0), Unalign(0), PostAlign(0) {}
97 /// Compute the offset immediately following this block.
98 unsigned postOffset() const { return Offset + Size; }
101 std::vector<BasicBlockInfo> BBInfo;
103 /// WaterList - A sorted list of basic blocks where islands could be placed
104 /// (i.e. blocks that don't fall through to the following block, due
105 /// to a return, unreachable, or unconditional branch).
106 std::vector<MachineBasicBlock*> WaterList;
108 /// NewWaterList - The subset of WaterList that was created since the
109 /// previous iteration by inserting unconditional branches.
110 SmallSet<MachineBasicBlock*, 4> NewWaterList;
112 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
114 /// CPUser - One user of a constant pool, keeping the machine instruction
115 /// pointer, the constant pool being referenced, and the max displacement
116 /// allowed from the instruction to the CP. The HighWaterMark records the
117 /// highest basic block where a new CPEntry can be placed. To ensure this
118 /// pass terminates, the CP entries are initially placed at the end of the
119 /// function and then move monotonically to lower addresses. The
120 /// exception to this rule is when the current CP entry for a particular
121 /// CPUser is out of range, but there is another CP entry for the same
122 /// constant value in range. We want to use the existing in-range CP
123 /// entry, but if it later moves out of range, the search for new water
124 /// should resume where it left off. The HighWaterMark is used to record
129 MachineBasicBlock *HighWaterMark;
133 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
134 bool neg, bool soimm)
135 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
136 HighWaterMark = CPEMI->getParent();
140 /// CPUsers - Keep track of all of the machine instructions that use various
141 /// constant pools and their max displacement.
142 std::vector<CPUser> CPUsers;
144 /// CPEntry - One per constant pool entry, keeping the machine instruction
145 /// pointer, the constpool index, and the number of CPUser's which
146 /// reference this entry.
151 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
152 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
155 /// CPEntries - Keep track of all of the constant pool entry machine
156 /// instructions. For each original constpool index (i.e. those that
157 /// existed upon entry to this pass), it keeps a vector of entries.
158 /// Original elements are cloned as we go along; the clones are
159 /// put in the vector of the original element, but have distinct CPIs.
160 std::vector<std::vector<CPEntry> > CPEntries;
162 /// ImmBranch - One per immediate branch, keeping the machine instruction
163 /// pointer, conditional or unconditional, the max displacement,
164 /// and (if isCond is true) the corresponding unconditional branch
168 unsigned MaxDisp : 31;
171 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
172 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
175 /// ImmBranches - Keep track of all the immediate branch instructions.
177 std::vector<ImmBranch> ImmBranches;
179 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
181 SmallVector<MachineInstr*, 4> PushPopMIs;
183 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
184 SmallVector<MachineInstr*, 4> T2JumpTables;
186 /// HasFarJump - True if any far jump instruction has been emitted during
187 /// the branch fix up pass.
190 /// HasInlineAsm - True if the function contains inline assembly.
193 const ARMInstrInfo *TII;
194 const ARMSubtarget *STI;
195 ARMFunctionInfo *AFI;
201 ARMConstantIslands() : MachineFunctionPass(ID) {}
203 virtual bool runOnMachineFunction(MachineFunction &MF);
205 virtual const char *getPassName() const {
206 return "ARM constant island placement and branch shortening pass";
210 void DoInitialPlacement(MachineFunction &MF,
211 std::vector<MachineInstr*> &CPEMIs);
212 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
213 void JumpTableFunctionScan(MachineFunction &MF);
214 void InitialFunctionScan(MachineFunction &MF,
215 const std::vector<MachineInstr*> &CPEMIs);
216 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
217 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
218 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
219 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
220 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
221 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
222 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
223 MachineBasicBlock *&NewMBB);
224 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
225 void RemoveDeadCPEMI(MachineInstr *CPEMI);
226 bool RemoveUnusedCPEntries();
227 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
228 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
229 bool DoDump = false);
230 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
232 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
233 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
234 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
235 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
236 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
237 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
238 bool UndoLRSpillRestore();
239 bool OptimizeThumb2Instructions(MachineFunction &MF);
240 bool OptimizeThumb2Branches(MachineFunction &MF);
241 bool ReorderThumb2JumpTables(MachineFunction &MF);
242 bool OptimizeThumb2JumpTables(MachineFunction &MF);
243 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
244 MachineBasicBlock *JTBB);
246 void ComputeBlockSize(const MachineBasicBlock *MBB);
247 unsigned GetOffsetOf(MachineInstr *MI) const;
249 void verify(MachineFunction &MF);
251 char ARMConstantIslands::ID = 0;
254 /// verify - check BBOffsets, BBSizes, alignment of islands
255 void ARMConstantIslands::verify(MachineFunction &MF) {
256 for (unsigned i = 1, e = BBInfo.size(); i != e; ++i)
257 assert(BBInfo[i-1].postOffset() == BBInfo[i].Offset);
261 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
263 MachineBasicBlock *MBB = MBBI;
265 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
266 unsigned MBBId = MBB->getNumber();
267 assert(HasInlineAsm ||
268 (BBInfo[MBBId].Offset%4 == 0 && BBInfo[MBBId].Size%4 == 0) ||
269 (BBInfo[MBBId].Offset%4 != 0 && BBInfo[MBBId].Size%4 != 0));
272 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
273 CPUser &U = CPUsers[i];
274 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
275 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
276 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
277 UserOffset - CPEOffset;
278 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
283 /// print block size and offset information - debugging
284 void ARMConstantIslands::dumpBBs() {
285 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
286 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
287 << " size " << BBInfo[J].Size << "\n");
291 /// createARMConstantIslandPass - returns an instance of the constpool
293 FunctionPass *llvm::createARMConstantIslandPass() {
294 return new ARMConstantIslands();
297 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
298 MachineConstantPool &MCP = *MF.getConstantPool();
300 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
301 AFI = MF.getInfo<ARMFunctionInfo>();
302 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
304 isThumb = AFI->isThumbFunction();
305 isThumb1 = AFI->isThumb1OnlyFunction();
306 isThumb2 = AFI->isThumb2Function();
309 HasInlineAsm = false;
311 // Renumber all of the machine basic blocks in the function, guaranteeing that
312 // the numbers agree with the position of the block in the function.
315 // Try to reorder and otherwise adjust the block layout to make good use
316 // of the TB[BH] instructions.
317 bool MadeChange = false;
318 if (isThumb2 && AdjustJumpTableBlocks) {
319 JumpTableFunctionScan(MF);
320 MadeChange |= ReorderThumb2JumpTables(MF);
321 // Data is out of date, so clear it. It'll be re-computed later.
322 T2JumpTables.clear();
323 // Blocks may have shifted around. Keep the numbering up to date.
327 // Thumb1 functions containing constant pools get 4-byte alignment.
328 // This is so we can keep exact track of where the alignment padding goes.
330 // ARM and Thumb2 functions need to be 4-byte aligned.
332 MF.EnsureAlignment(2); // 2 = log2(4)
334 // Perform the initial placement of the constant pool entries. To start with,
335 // we put them all at the end of the function.
336 std::vector<MachineInstr*> CPEMIs;
337 if (!MCP.isEmpty()) {
338 DoInitialPlacement(MF, CPEMIs);
340 MF.EnsureAlignment(2); // 2 = log2(4)
343 /// The next UID to take is the first unused one.
344 AFI->initPICLabelUId(CPEMIs.size());
346 // Do the initial scan of the function, building up information about the
347 // sizes of each block, the location of all the water, and finding all of the
348 // constant pool users.
349 InitialFunctionScan(MF, CPEMIs);
354 /// Remove dead constant pool entries.
355 MadeChange |= RemoveUnusedCPEntries();
357 // Iteratively place constant pool entries and fix up branches until there
359 unsigned NoCPIters = 0, NoBRIters = 0;
361 bool CPChange = false;
362 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
363 CPChange |= HandleConstantPoolUser(MF, i);
364 if (CPChange && ++NoCPIters > 30)
365 llvm_unreachable("Constant Island pass failed to converge!");
368 // Clear NewWaterList now. If we split a block for branches, it should
369 // appear as "new water" for the next iteration of constant pool placement.
370 NewWaterList.clear();
372 bool BRChange = false;
373 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
374 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
375 if (BRChange && ++NoBRIters > 30)
376 llvm_unreachable("Branch Fix Up pass failed to converge!");
379 if (!CPChange && !BRChange)
384 // Shrink 32-bit Thumb2 branch, load, and store instructions.
385 if (isThumb2 && !STI->prefers32BitThumb())
386 MadeChange |= OptimizeThumb2Instructions(MF);
388 // After a while, this might be made debug-only, but it is not expensive.
391 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
392 // undo the spill / restore of LR if possible.
393 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
394 MadeChange |= UndoLRSpillRestore();
396 // Save the mapping between original and cloned constpool entries.
397 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
398 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
399 const CPEntry & CPE = CPEntries[i][j];
400 AFI->recordCPEClone(i, CPE.CPI);
404 DEBUG(errs() << '\n'; dumpBBs());
412 T2JumpTables.clear();
417 /// DoInitialPlacement - Perform the initial placement of the constant pool
418 /// entries. To start with, we put them all at the end of the function.
419 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
420 std::vector<MachineInstr*> &CPEMIs) {
421 // Create the basic block to hold the CPE's.
422 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
425 // Mark the basic block as 4-byte aligned as required by the const-pool.
428 // Add all of the constants from the constant pool to the end block, use an
429 // identity mapping of CPI's to CPE's.
430 const std::vector<MachineConstantPoolEntry> &CPs =
431 MF.getConstantPool()->getConstants();
433 const TargetData &TD = *MF.getTarget().getTargetData();
434 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
435 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
436 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
437 // we would have to pad them out or something so that instructions stay
439 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
440 MachineInstr *CPEMI =
441 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
442 .addImm(i).addConstantPoolIndex(i).addImm(Size);
443 CPEMIs.push_back(CPEMI);
445 // Add a new CPEntry, but no corresponding CPUser yet.
446 std::vector<CPEntry> CPEs;
447 CPEs.push_back(CPEntry(CPEMI, i));
448 CPEntries.push_back(CPEs);
450 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
455 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
456 /// into the block immediately after it.
457 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
458 // Get the next machine basic block in the function.
459 MachineFunction::iterator MBBI = MBB;
460 // Can't fall off end of function.
461 if (llvm::next(MBBI) == MBB->getParent()->end())
464 MachineBasicBlock *NextBB = llvm::next(MBBI);
465 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
466 E = MBB->succ_end(); I != E; ++I)
473 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
474 /// look up the corresponding CPEntry.
475 ARMConstantIslands::CPEntry
476 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
477 const MachineInstr *CPEMI) {
478 std::vector<CPEntry> &CPEs = CPEntries[CPI];
479 // Number of entries per constpool index should be small, just do a
481 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
482 if (CPEs[i].CPEMI == CPEMI)
488 /// JumpTableFunctionScan - Do a scan of the function, building up
489 /// information about the sizes of each block and the locations of all
491 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
492 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
494 MachineBasicBlock &MBB = *MBBI;
496 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
498 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
499 T2JumpTables.push_back(I);
503 /// InitialFunctionScan - Do the initial scan of the function, building up
504 /// information about the sizes of each block, the location of all the water,
505 /// and finding all of the constant pool users.
506 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
507 const std::vector<MachineInstr*> &CPEMIs) {
508 // First thing, see if the function has any inline assembly in it. If so,
509 // we have to be conservative about alignment assumptions, as we don't
510 // know for sure the size of any instructions in the inline assembly.
511 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
513 MachineBasicBlock &MBB = *MBBI;
514 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
516 if (I->getOpcode() == ARM::INLINEASM)
521 BBInfo.resize(MF.getNumBlockIDs());
523 // Now go back through the instructions and build up our data structures.
525 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
527 MachineBasicBlock &MBB = *MBBI;
528 BasicBlockInfo &BBI = BBInfo[MBB.getNumber()];
531 // If this block doesn't fall through into the next MBB, then this is
532 // 'water' that a constant pool island could be placed.
533 if (!BBHasFallthrough(&MBB))
534 WaterList.push_back(&MBB);
536 unsigned MBBSize = 0;
537 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
539 if (I->isDebugValue())
541 // Add instruction size to MBBSize.
542 MBBSize += TII->GetInstSizeInBytes(I);
544 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
545 // The actual size may be smaller, but still a multiple of the instr size.
546 if (I->isInlineAsm())
547 BBI.Unalign = isThumb ? 1 : 2;
549 int Opc = I->getOpcode();
550 if (I->getDesc().isBranch()) {
557 continue; // Ignore other JT branches
559 // A Thumb1 table jump may involve padding; for the offsets to
560 // be right, functions containing these must be 4-byte aligned.
561 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
562 // table entries. So this code checks whether offset of tBR_JTr + 2
563 // is aligned. That is held in Offset+MBBSize, which already has
564 // 2 added in for the size of the mov pc instruction.
565 MF.EnsureAlignment(2U);
567 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
568 // FIXME: Add a pseudo ALIGN instruction instead.
569 MBBSize += 2; // padding
570 continue; // Does not get an entry in ImmBranches
572 T2JumpTables.push_back(I);
573 continue; // Does not get an entry in ImmBranches
604 // Record this immediate branch.
605 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
606 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
609 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
610 PushPopMIs.push_back(I);
612 if (Opc == ARM::CONSTPOOL_ENTRY)
615 // Scan the instructions for constant pool operands.
616 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
617 if (I->getOperand(op).isCPI()) {
618 // We found one. The addressing mode tells us the max displacement
619 // from the PC that this instruction permits.
621 // Basic size info comes from the TSFlags field.
625 bool IsSoImm = false;
629 llvm_unreachable("Unknown addressing mode for CP reference!");
632 // Taking the address of a CP entry.
634 // This takes a SoImm, which is 8 bit immediate rotated. We'll
635 // pretend the maximum offset is 255 * 4. Since each instruction
636 // 4 byte wide, this is always correct. We'll check for other
637 // displacements that fits in a SoImm as well.
643 case ARM::t2LEApcrel:
655 Bits = 12; // +-offset_12
661 Scale = 4; // +(offset_8*4)
667 Scale = 4; // +-(offset_8*4)
672 // Remember that this is a user of a CP entry.
673 unsigned CPI = I->getOperand(op).getIndex();
674 MachineInstr *CPEMI = CPEMIs[CPI];
675 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
676 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
678 // Increment corresponding CPEntry reference count.
679 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
680 assert(CPE && "Cannot find a corresponding CPEntry!");
683 // Instructions can only use one CP entry, don't bother scanning the
684 // rest of the operands.
689 // In thumb mode, if this block is a constpool island, we may need padding
690 // so it's aligned on 4 byte boundary.
693 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
694 ((Offset%4) != 0 || HasInlineAsm))
702 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
703 /// This function updates BBInfo directly.
704 void ARMConstantIslands::ComputeBlockSize(const MachineBasicBlock *MBB) {
705 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
710 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
712 BBI.Size += TII->GetInstSizeInBytes(I);
713 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
714 // The actual size may be smaller, but still a multiple of the instr size.
715 if (I->isInlineAsm())
716 BBI.Unalign = isThumb ? 1 : 2;
719 // tBR_JTr contains a .align 2 directive.
720 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr)
724 /// GetOffsetOf - Return the current offset of the specified machine instruction
725 /// from the start of the function. This offset changes as stuff is moved
726 /// around inside the function.
727 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
728 MachineBasicBlock *MBB = MI->getParent();
730 // The offset is composed of two things: the sum of the sizes of all MBB's
731 // before this instruction's block, and the offset from the start of the block
733 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
735 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
736 // alignment padding, and compensate if so.
738 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
739 (Offset%4 != 0 || HasInlineAsm))
742 // Sum instructions before MI in MBB.
743 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
744 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
745 if (&*I == MI) return Offset;
746 Offset += TII->GetInstSizeInBytes(I);
750 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
752 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
753 const MachineBasicBlock *RHS) {
754 return LHS->getNumber() < RHS->getNumber();
757 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
758 /// machine function, it upsets all of the block numbers. Renumber the blocks
759 /// and update the arrays that parallel this numbering.
760 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
761 // Renumber the MBB's to keep them consecutive.
762 NewBB->getParent()->RenumberBlocks(NewBB);
764 // Insert an entry into BBInfo to align it properly with the (newly
765 // renumbered) block numbers.
766 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
768 // Next, update WaterList. Specifically, we need to add NewMBB as having
769 // available water after it.
771 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
773 WaterList.insert(IP, NewBB);
777 /// Split the basic block containing MI into two blocks, which are joined by
778 /// an unconditional branch. Update data structures and renumber blocks to
779 /// account for this change and returns the newly created block.
780 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
781 MachineBasicBlock *OrigBB = MI->getParent();
782 MachineFunction &MF = *OrigBB->getParent();
784 // Create a new MBB for the code after the OrigBB.
785 MachineBasicBlock *NewBB =
786 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
787 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
788 MF.insert(MBBI, NewBB);
790 // Splice the instructions starting with MI over to NewBB.
791 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
793 // Add an unconditional branch from OrigBB to NewBB.
794 // Note the new unconditional branch is not being recorded.
795 // There doesn't seem to be meaningful DebugInfo available; this doesn't
796 // correspond to anything in the source.
797 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
799 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
801 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
802 .addImm(ARMCC::AL).addReg(0);
805 // Update the CFG. All succs of OrigBB are now succs of NewBB.
806 NewBB->transferSuccessors(OrigBB);
808 // OrigBB branches to NewBB.
809 OrigBB->addSuccessor(NewBB);
811 // Update internal data structures to account for the newly inserted MBB.
812 // This is almost the same as UpdateForInsertedWaterBlock, except that
813 // the Water goes after OrigBB, not NewBB.
814 MF.RenumberBlocks(NewBB);
816 // Insert an entry into BBInfo to align it properly with the (newly
817 // renumbered) block numbers.
818 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
820 // Next, update WaterList. Specifically, we need to add OrigMBB as having
821 // available water after it (but not if it's already there, which happens
822 // when splitting before a conditional branch that is followed by an
823 // unconditional branch - in that case we want to insert NewBB).
825 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
827 MachineBasicBlock* WaterBB = *IP;
828 if (WaterBB == OrigBB)
829 WaterList.insert(llvm::next(IP), NewBB);
831 WaterList.insert(IP, OrigBB);
832 NewWaterList.insert(OrigBB);
834 unsigned OrigBBI = OrigBB->getNumber();
835 unsigned NewBBI = NewBB->getNumber();
837 int delta = isThumb1 ? 2 : 4;
839 // Figure out how large the OrigBB is. As the first half of the original
840 // block, it cannot contain a tablejump. The size includes
841 // the new jump we added. (It should be possible to do this without
842 // recounting everything, but it's very confusing, and this is rarely
844 ComputeBlockSize(OrigBB);
846 // ...and adjust BBOffsets for NewBB accordingly.
847 BBInfo[NewBBI].Offset = BBInfo[OrigBBI].postOffset();
849 // Figure out how large the NewMBB is. As the second half of the original
850 // block, it may contain a tablejump.
851 ComputeBlockSize(NewBB);
853 MachineInstr* ThumbJTMI = prior(NewBB->end());
854 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
855 // We've added another 2-byte instruction before this tablejump, which
856 // means we will always need padding if we didn't before, and vice versa.
858 // The original offset of the jump instruction was:
859 unsigned OrigOffset = BBInfo[OrigBBI].postOffset() - delta;
860 if (OrigOffset%4 == 0) {
861 // We had padding before and now we don't. No net change in code size.
864 // We didn't have padding before and now we do.
865 BBInfo[NewBBI].Size += 2;
870 // All BBOffsets following these blocks must be modified.
872 AdjustBBOffsetsAfter(NewBB);
877 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
878 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
879 /// constant pool entry).
880 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
881 unsigned TrialOffset, unsigned MaxDisp,
882 bool NegativeOK, bool IsSoImm) {
883 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
884 // purposes of the displacement computation; compensate for that here.
885 // Effectively, the valid range of displacements is 2 bytes smaller for such
887 unsigned TotalAdj = 0;
888 if (isThumb && UserOffset%4 !=0) {
892 // CPEs will be rounded up to a multiple of 4.
893 if (isThumb && TrialOffset%4 != 0) {
898 // In Thumb2 mode, later branch adjustments can shift instructions up and
899 // cause alignment change. In the worst case scenario this can cause the
900 // user's effective address to be subtracted by 2 and the CPE's address to
902 if (isThumb2 && TotalAdj != 4)
903 MaxDisp -= (4 - TotalAdj);
905 if (UserOffset <= TrialOffset) {
906 // User before the Trial.
907 if (TrialOffset - UserOffset <= MaxDisp)
909 // FIXME: Make use full range of soimm values.
910 } else if (NegativeOK) {
911 if (UserOffset - TrialOffset <= MaxDisp)
913 // FIXME: Make use full range of soimm values.
918 /// WaterIsInRange - Returns true if a CPE placed after the specified
919 /// Water (a basic block) will be in range for the specific MI.
921 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
922 MachineBasicBlock* Water, CPUser &U) {
923 unsigned MaxDisp = U.MaxDisp;
924 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
926 // If the CPE is to be inserted before the instruction, that will raise
927 // the offset of the instruction.
928 if (CPEOffset < UserOffset)
929 UserOffset += U.CPEMI->getOperand(2).getImm();
931 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
934 /// CPEIsInRange - Returns true if the distance between specific MI and
935 /// specific ConstPool entry instruction can fit in MI's displacement field.
936 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
937 MachineInstr *CPEMI, unsigned MaxDisp,
938 bool NegOk, bool DoDump) {
939 unsigned CPEOffset = GetOffsetOf(CPEMI);
940 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
943 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
944 << " max delta=" << MaxDisp
945 << " insn address=" << UserOffset
946 << " CPE address=" << CPEOffset
947 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
950 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
954 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
955 /// unconditionally branches to its only successor.
956 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
957 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
960 MachineBasicBlock *Succ = *MBB->succ_begin();
961 MachineBasicBlock *Pred = *MBB->pred_begin();
962 MachineInstr *PredMI = &Pred->back();
963 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
964 || PredMI->getOpcode() == ARM::t2B)
965 return PredMI->getOperand(0).getMBB() == Succ;
970 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
971 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
972 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
974 unsigned OldOffset = BBInfo[i].Offset;
975 BBInfo[i].Offset = BBInfo[i-1].postOffset();
976 int delta = BBInfo[i].Offset - OldOffset;
977 // If some existing blocks have padding, adjust the padding as needed, a
978 // bit tricky. delta can be negative so don't use % on that.
981 MachineBasicBlock *MBB = MBBI;
982 if (!MBB->empty() && !HasInlineAsm) {
983 // Constant pool entries require padding.
984 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
985 if ((OldOffset%4) == 0 && (BBInfo[i].Offset%4) != 0) {
989 } else if ((OldOffset%4) != 0 && (BBInfo[i].Offset%4) == 0) {
990 // remove existing padding
995 // Thumb1 jump tables require padding. They should be at the end;
996 // following unconditional branches are removed by AnalyzeBranch.
997 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
998 // table entries. So this code checks whether offset of tBR_JTr
999 // is aligned; if it is, the offset of the jump table following the
1000 // instruction will not be aligned, and we need padding.
1001 MachineInstr *ThumbJTMI = prior(MBB->end());
1002 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
1003 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
1004 unsigned OldMIOffset = NewMIOffset - delta;
1005 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
1006 // remove existing padding
1007 BBInfo[i].Size -= 2;
1008 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
1010 BBInfo[i].Size += 2;
1014 MBBI = llvm::next(MBBI);
1018 /// DecrementOldEntry - find the constant pool entry with index CPI
1019 /// and instruction CPEMI, and decrement its refcount. If the refcount
1020 /// becomes 0 remove the entry and instruction. Returns true if we removed
1021 /// the entry, false if we didn't.
1023 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
1024 // Find the old entry. Eliminate it if it is no longer used.
1025 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1026 assert(CPE && "Unexpected!");
1027 if (--CPE->RefCount == 0) {
1028 RemoveDeadCPEMI(CPEMI);
1036 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1037 /// if not, see if an in-range clone of the CPE is in range, and if so,
1038 /// change the data structures so the user references the clone. Returns:
1039 /// 0 = no existing entry found
1040 /// 1 = entry found, and there were no code insertions or deletions
1041 /// 2 = entry found, and there were code insertions or deletions
1042 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1044 MachineInstr *UserMI = U.MI;
1045 MachineInstr *CPEMI = U.CPEMI;
1047 // Check to see if the CPE is already in-range.
1048 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1049 DEBUG(errs() << "In range\n");
1053 // No. Look for previously created clones of the CPE that are in range.
1054 unsigned CPI = CPEMI->getOperand(1).getIndex();
1055 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1056 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1057 // We already tried this one
1058 if (CPEs[i].CPEMI == CPEMI)
1060 // Removing CPEs can leave empty entries, skip
1061 if (CPEs[i].CPEMI == NULL)
1063 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1064 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1065 << CPEs[i].CPI << "\n");
1066 // Point the CPUser node to the replacement
1067 U.CPEMI = CPEs[i].CPEMI;
1068 // Change the CPI in the instruction operand to refer to the clone.
1069 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1070 if (UserMI->getOperand(j).isCPI()) {
1071 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1074 // Adjust the refcount of the clone...
1076 // ...and the original. If we didn't remove the old entry, none of the
1077 // addresses changed, so we don't need another pass.
1078 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1084 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1085 /// the specific unconditional branch instruction.
1086 static inline unsigned getUnconditionalBrDisp(int Opc) {
1089 return ((1<<10)-1)*2;
1091 return ((1<<23)-1)*2;
1096 return ((1<<23)-1)*4;
1099 /// LookForWater - Look for an existing entry in the WaterList in which
1100 /// we can place the CPE referenced from U so it's within range of U's MI.
1101 /// Returns true if found, false if not. If it returns true, WaterIter
1102 /// is set to the WaterList entry. For Thumb, prefer water that will not
1103 /// introduce padding to water that will. To ensure that this pass
1104 /// terminates, the CPE location for a particular CPUser is only allowed to
1105 /// move to a lower address, so search backward from the end of the list and
1106 /// prefer the first water that is in range.
1107 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1108 water_iterator &WaterIter) {
1109 if (WaterList.empty())
1112 bool FoundWaterThatWouldPad = false;
1113 water_iterator IPThatWouldPad;
1114 for (water_iterator IP = prior(WaterList.end()),
1115 B = WaterList.begin();; --IP) {
1116 MachineBasicBlock* WaterBB = *IP;
1117 // Check if water is in range and is either at a lower address than the
1118 // current "high water mark" or a new water block that was created since
1119 // the previous iteration by inserting an unconditional branch. In the
1120 // latter case, we want to allow resetting the high water mark back to
1121 // this new water since we haven't seen it before. Inserting branches
1122 // should be relatively uncommon and when it does happen, we want to be
1123 // sure to take advantage of it for all the CPEs near that block, so that
1124 // we don't insert more branches than necessary.
1125 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1126 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1127 NewWaterList.count(WaterBB))) {
1128 unsigned WBBId = WaterBB->getNumber();
1129 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1130 // This is valid Water, but would introduce padding. Remember
1131 // it in case we don't find any Water that doesn't do this.
1132 if (!FoundWaterThatWouldPad) {
1133 FoundWaterThatWouldPad = true;
1134 IPThatWouldPad = IP;
1144 if (FoundWaterThatWouldPad) {
1145 WaterIter = IPThatWouldPad;
1151 /// CreateNewWater - No existing WaterList entry will work for
1152 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1153 /// block is used if in range, and the conditional branch munged so control
1154 /// flow is correct. Otherwise the block is split to create a hole with an
1155 /// unconditional branch around it. In either case NewMBB is set to a
1156 /// block following which the new island can be inserted (the WaterList
1157 /// is not adjusted).
1158 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1159 unsigned UserOffset,
1160 MachineBasicBlock *&NewMBB) {
1161 CPUser &U = CPUsers[CPUserIndex];
1162 MachineInstr *UserMI = U.MI;
1163 MachineInstr *CPEMI = U.CPEMI;
1164 MachineBasicBlock *UserMBB = UserMI->getParent();
1165 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
1166 assert(OffsetOfNextBlock == BBInfo[UserMBB->getNumber()+1].Offset);
1168 // If the block does not end in an unconditional branch already, and if the
1169 // end of the block is within range, make new water there. (The addition
1170 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1171 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1172 // inside OffsetIsInRange.
1173 if (BBHasFallthrough(UserMBB) &&
1174 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1175 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1176 DEBUG(errs() << "Split at end of block\n");
1177 if (&UserMBB->back() == UserMI)
1178 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1179 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1180 // Add an unconditional branch from UserMBB to fallthrough block.
1181 // Record it for branch lengthening; this new branch will not get out of
1182 // range, but if the preceding conditional branch is out of range, the
1183 // targets will be exchanged, and the altered branch may be out of
1184 // range, so the machinery has to know about it.
1185 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1187 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1189 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1190 .addImm(ARMCC::AL).addReg(0);
1191 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1192 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1193 MaxDisp, false, UncondBr));
1194 int delta = isThumb1 ? 2 : 4;
1195 BBInfo[UserMBB->getNumber()].Size += delta;
1196 AdjustBBOffsetsAfter(UserMBB);
1198 // What a big block. Find a place within the block to split it.
1199 // This is a little tricky on Thumb1 since instructions are 2 bytes
1200 // and constant pool entries are 4 bytes: if instruction I references
1201 // island CPE, and instruction I+1 references CPE', it will
1202 // not work well to put CPE as far forward as possible, since then
1203 // CPE' cannot immediately follow it (that location is 2 bytes
1204 // farther away from I+1 than CPE was from I) and we'd need to create
1205 // a new island. So, we make a first guess, then walk through the
1206 // instructions between the one currently being looked at and the
1207 // possible insertion point, and make sure any other instructions
1208 // that reference CPEs will be able to use the same island area;
1209 // if not, we back up the insertion point.
1211 // The 4 in the following is for the unconditional branch we'll be
1212 // inserting (allows for long branch on Thumb1). Alignment of the
1213 // island is handled inside OffsetIsInRange.
1214 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1215 // This could point off the end of the block if we've already got
1216 // constant pool entries following this block; only the last one is
1217 // in the water list. Back past any possible branches (allow for a
1218 // conditional and a maximally long unconditional).
1219 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1220 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1222 unsigned EndInsertOffset = BaseInsertOffset +
1223 CPEMI->getOperand(2).getImm();
1224 MachineBasicBlock::iterator MI = UserMI;
1226 unsigned CPUIndex = CPUserIndex+1;
1227 unsigned NumCPUsers = CPUsers.size();
1228 MachineInstr *LastIT = 0;
1229 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1230 Offset < BaseInsertOffset;
1231 Offset += TII->GetInstSizeInBytes(MI),
1232 MI = llvm::next(MI)) {
1233 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1234 CPUser &U = CPUsers[CPUIndex];
1235 if (!OffsetIsInRange(Offset, EndInsertOffset,
1236 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1237 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1238 EndInsertOffset -= (isThumb1 ? 2 : 4);
1240 // This is overly conservative, as we don't account for CPEMIs
1241 // being reused within the block, but it doesn't matter much.
1242 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1246 // Remember the last IT instruction.
1247 if (MI->getOpcode() == ARM::t2IT)
1251 DEBUG(errs() << "Split in middle of big block\n");
1254 // Avoid splitting an IT block.
1256 unsigned PredReg = 0;
1257 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1258 if (CC != ARMCC::AL)
1261 NewMBB = SplitBlockBeforeInstr(MI);
1265 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1266 /// is out-of-range. If so, pick up the constant pool value and move it some
1267 /// place in-range. Return true if we changed any addresses (thus must run
1268 /// another pass of branch lengthening), false otherwise.
1269 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1270 unsigned CPUserIndex) {
1271 CPUser &U = CPUsers[CPUserIndex];
1272 MachineInstr *UserMI = U.MI;
1273 MachineInstr *CPEMI = U.CPEMI;
1274 unsigned CPI = CPEMI->getOperand(1).getIndex();
1275 unsigned Size = CPEMI->getOperand(2).getImm();
1276 // Compute this only once, it's expensive. The 4 or 8 is the value the
1277 // hardware keeps in the PC.
1278 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1280 // See if the current entry is within range, or there is a clone of it
1282 int result = LookForExistingCPEntry(U, UserOffset);
1283 if (result==1) return false;
1284 else if (result==2) return true;
1286 // No existing clone of this CPE is within range.
1287 // We will be generating a new clone. Get a UID for it.
1288 unsigned ID = AFI->createPICLabelUId();
1290 // Look for water where we can place this CPE.
1291 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1292 MachineBasicBlock *NewMBB;
1294 if (LookForWater(U, UserOffset, IP)) {
1295 DEBUG(errs() << "found water in range\n");
1296 MachineBasicBlock *WaterBB = *IP;
1298 // If the original WaterList entry was "new water" on this iteration,
1299 // propagate that to the new island. This is just keeping NewWaterList
1300 // updated to match the WaterList, which will be updated below.
1301 if (NewWaterList.count(WaterBB)) {
1302 NewWaterList.erase(WaterBB);
1303 NewWaterList.insert(NewIsland);
1305 // The new CPE goes before the following block (NewMBB).
1306 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1310 DEBUG(errs() << "No water found\n");
1311 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1313 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1314 // called while handling branches so that the water will be seen on the
1315 // next iteration for constant pools, but in this context, we don't want
1316 // it. Check for this so it will be removed from the WaterList.
1317 // Also remove any entry from NewWaterList.
1318 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1319 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1320 if (IP != WaterList.end())
1321 NewWaterList.erase(WaterBB);
1323 // We are adding new water. Update NewWaterList.
1324 NewWaterList.insert(NewIsland);
1327 // Remove the original WaterList entry; we want subsequent insertions in
1328 // this vicinity to go after the one we're about to insert. This
1329 // considerably reduces the number of times we have to move the same CPE
1330 // more than once and is also important to ensure the algorithm terminates.
1331 if (IP != WaterList.end())
1332 WaterList.erase(IP);
1334 // Okay, we know we can put an island before NewMBB now, do it!
1335 MF.insert(NewMBB, NewIsland);
1337 // Update internal data structures to account for the newly inserted MBB.
1338 UpdateForInsertedWaterBlock(NewIsland);
1340 // Decrement the old entry, and remove it if refcount becomes 0.
1341 DecrementOldEntry(CPI, CPEMI);
1343 // Now that we have an island to add the CPE to, clone the original CPE and
1344 // add it to the island.
1345 U.HighWaterMark = NewIsland;
1346 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1347 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1348 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1351 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1352 NewIsland->setAlignment(2);
1354 BBInfo[NewIsland->getNumber()].Offset = BBInfo[NewMBB->getNumber()].Offset;
1355 // Compensate for .align 2 in thumb mode.
1356 if (isThumb && (BBInfo[NewIsland->getNumber()].Offset%4 != 0 || HasInlineAsm))
1358 // Increase the size of the island block to account for the new entry.
1359 BBInfo[NewIsland->getNumber()].Size += Size;
1360 AdjustBBOffsetsAfter(NewIsland);
1362 // Finally, change the CPI in the instruction operand to be ID.
1363 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1364 if (UserMI->getOperand(i).isCPI()) {
1365 UserMI->getOperand(i).setIndex(ID);
1369 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1370 << '\t' << *UserMI);
1375 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1376 /// sizes and offsets of impacted basic blocks.
1377 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1378 MachineBasicBlock *CPEBB = CPEMI->getParent();
1379 unsigned Size = CPEMI->getOperand(2).getImm();
1380 CPEMI->eraseFromParent();
1381 BBInfo[CPEBB->getNumber()].Size -= Size;
1382 // All succeeding offsets have the current size value added in, fix this.
1383 if (CPEBB->empty()) {
1384 // In thumb1 mode, the size of island may be padded by two to compensate for
1385 // the alignment requirement. Then it will now be 2 when the block is
1386 // empty, so fix this.
1387 // All succeeding offsets have the current size value added in, fix this.
1388 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1389 Size += BBInfo[CPEBB->getNumber()].Size;
1390 BBInfo[CPEBB->getNumber()].Size = 0;
1393 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1394 CPEBB->setAlignment(0);
1396 AdjustBBOffsetsAfter(CPEBB);
1397 // An island has only one predecessor BB and one successor BB. Check if
1398 // this BB's predecessor jumps directly to this BB's successor. This
1399 // shouldn't happen currently.
1400 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1401 // FIXME: remove the empty blocks after all the work is done?
1404 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1406 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1407 unsigned MadeChange = false;
1408 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1409 std::vector<CPEntry> &CPEs = CPEntries[i];
1410 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1411 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1412 RemoveDeadCPEMI(CPEs[j].CPEMI);
1413 CPEs[j].CPEMI = NULL;
1421 /// BBIsInRange - Returns true if the distance between specific MI and
1422 /// specific BB can fit in MI's displacement field.
1423 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1425 unsigned PCAdj = isThumb ? 4 : 8;
1426 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1427 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1429 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1430 << " from BB#" << MI->getParent()->getNumber()
1431 << " max delta=" << MaxDisp
1432 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1433 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1435 if (BrOffset <= DestOffset) {
1436 // Branch before the Dest.
1437 if (DestOffset-BrOffset <= MaxDisp)
1440 if (BrOffset-DestOffset <= MaxDisp)
1446 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1447 /// away to fit in its displacement field.
1448 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1449 MachineInstr *MI = Br.MI;
1450 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1452 // Check to see if the DestBB is already in-range.
1453 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1457 return FixUpUnconditionalBr(MF, Br);
1458 return FixUpConditionalBr(MF, Br);
1461 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1462 /// too far away to fit in its displacement field. If the LR register has been
1463 /// spilled in the epilogue, then we can use BL to implement a far jump.
1464 /// Otherwise, add an intermediate branch instruction to a branch.
1466 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1467 MachineInstr *MI = Br.MI;
1468 MachineBasicBlock *MBB = MI->getParent();
1470 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1472 // Use BL to implement far jump.
1473 Br.MaxDisp = (1 << 21) * 2;
1474 MI->setDesc(TII->get(ARM::tBfar));
1475 BBInfo[MBB->getNumber()].Size += 2;
1476 AdjustBBOffsetsAfter(MBB);
1480 DEBUG(errs() << " Changed B to long jump " << *MI);
1485 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1486 /// far away to fit in its displacement field. It is converted to an inverse
1487 /// conditional branch + an unconditional branch to the destination.
1489 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1490 MachineInstr *MI = Br.MI;
1491 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1493 // Add an unconditional branch to the destination and invert the branch
1494 // condition to jump over it:
1500 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1501 CC = ARMCC::getOppositeCondition(CC);
1502 unsigned CCReg = MI->getOperand(2).getReg();
1504 // If the branch is at the end of its MBB and that has a fall-through block,
1505 // direct the updated conditional branch to the fall-through block. Otherwise,
1506 // split the MBB before the next instruction.
1507 MachineBasicBlock *MBB = MI->getParent();
1508 MachineInstr *BMI = &MBB->back();
1509 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1513 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1514 BMI->getOpcode() == Br.UncondBr) {
1515 // Last MI in the BB is an unconditional branch. Can we simply invert the
1516 // condition and swap destinations:
1522 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1523 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1524 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1526 BMI->getOperand(0).setMBB(DestBB);
1527 MI->getOperand(0).setMBB(NewDest);
1528 MI->getOperand(1).setImm(CC);
1535 SplitBlockBeforeInstr(MI);
1536 // No need for the branch to the next block. We're adding an unconditional
1537 // branch to the destination.
1538 int delta = TII->GetInstSizeInBytes(&MBB->back());
1539 BBInfo[MBB->getNumber()].Size -= delta;
1540 MBB->back().eraseFromParent();
1541 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1543 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1545 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1546 << " also invert condition and change dest. to BB#"
1547 << NextBB->getNumber() << "\n");
1549 // Insert a new conditional branch and a new unconditional branch.
1550 // Also update the ImmBranch as well as adding a new entry for the new branch.
1551 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1552 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1553 Br.MI = &MBB->back();
1554 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1556 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1557 .addImm(ARMCC::AL).addReg(0);
1559 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1560 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1561 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1562 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1564 // Remove the old conditional branch. It may or may not still be in MBB.
1565 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1566 MI->eraseFromParent();
1567 AdjustBBOffsetsAfter(MBB);
1571 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1572 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1573 /// to do this if tBfar is not used.
1574 bool ARMConstantIslands::UndoLRSpillRestore() {
1575 bool MadeChange = false;
1576 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1577 MachineInstr *MI = PushPopMIs[i];
1578 // First two operands are predicates.
1579 if (MI->getOpcode() == ARM::tPOP_RET &&
1580 MI->getOperand(2).getReg() == ARM::PC &&
1581 MI->getNumExplicitOperands() == 3) {
1582 // Create the new insn and copy the predicate from the old.
1583 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1584 .addOperand(MI->getOperand(0))
1585 .addOperand(MI->getOperand(1));
1586 MI->eraseFromParent();
1593 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1594 bool MadeChange = false;
1596 // Shrink ADR and LDR from constantpool.
1597 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1598 CPUser &U = CPUsers[i];
1599 unsigned Opcode = U.MI->getOpcode();
1600 unsigned NewOpc = 0;
1605 case ARM::t2LEApcrel:
1606 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1607 NewOpc = ARM::tLEApcrel;
1613 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1614 NewOpc = ARM::tLDRpci;
1624 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1625 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1626 // FIXME: Check if offset is multiple of scale if scale is not 4.
1627 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1628 U.MI->setDesc(TII->get(NewOpc));
1629 MachineBasicBlock *MBB = U.MI->getParent();
1630 BBInfo[MBB->getNumber()].Size -= 2;
1631 AdjustBBOffsetsAfter(MBB);
1637 MadeChange |= OptimizeThumb2Branches(MF);
1638 MadeChange |= OptimizeThumb2JumpTables(MF);
1642 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1643 bool MadeChange = false;
1645 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1646 ImmBranch &Br = ImmBranches[i];
1647 unsigned Opcode = Br.MI->getOpcode();
1648 unsigned NewOpc = 0;
1666 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1667 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1668 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1669 Br.MI->setDesc(TII->get(NewOpc));
1670 MachineBasicBlock *MBB = Br.MI->getParent();
1671 BBInfo[MBB->getNumber()].Size -= 2;
1672 AdjustBBOffsetsAfter(MBB);
1678 Opcode = Br.MI->getOpcode();
1679 if (Opcode != ARM::tBcc)
1683 unsigned PredReg = 0;
1684 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1685 if (Pred == ARMCC::EQ)
1687 else if (Pred == ARMCC::NE)
1688 NewOpc = ARM::tCBNZ;
1691 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1692 // Check if the distance is within 126. Subtract starting offset by 2
1693 // because the cmp will be eliminated.
1694 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1695 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1696 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1697 MachineBasicBlock::iterator CmpMI = Br.MI;
1698 if (CmpMI != Br.MI->getParent()->begin()) {
1700 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1701 unsigned Reg = CmpMI->getOperand(0).getReg();
1702 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1703 if (Pred == ARMCC::AL &&
1704 CmpMI->getOperand(1).getImm() == 0 &&
1705 isARMLowRegister(Reg)) {
1706 MachineBasicBlock *MBB = Br.MI->getParent();
1707 MachineInstr *NewBR =
1708 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1709 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1710 CmpMI->eraseFromParent();
1711 Br.MI->eraseFromParent();
1713 BBInfo[MBB->getNumber()].Size -= 2;
1714 AdjustBBOffsetsAfter(MBB);
1726 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1727 /// jumptables when it's possible.
1728 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1729 bool MadeChange = false;
1731 // FIXME: After the tables are shrunk, can we get rid some of the
1732 // constantpool tables?
1733 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1734 if (MJTI == 0) return false;
1736 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1737 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1738 MachineInstr *MI = T2JumpTables[i];
1739 const MCInstrDesc &MCID = MI->getDesc();
1740 unsigned NumOps = MCID.getNumOperands();
1741 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
1742 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1743 unsigned JTI = JTOP.getIndex();
1744 assert(JTI < JT.size());
1747 bool HalfWordOk = true;
1748 unsigned JTOffset = GetOffsetOf(MI) + 4;
1749 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1750 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1751 MachineBasicBlock *MBB = JTBBs[j];
1752 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1753 // Negative offset is not ok. FIXME: We should change BB layout to make
1754 // sure all the branches are forward.
1755 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1757 unsigned TBHLimit = ((1<<16)-1)*2;
1758 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1760 if (!ByteOk && !HalfWordOk)
1764 if (ByteOk || HalfWordOk) {
1765 MachineBasicBlock *MBB = MI->getParent();
1766 unsigned BaseReg = MI->getOperand(0).getReg();
1767 bool BaseRegKill = MI->getOperand(0).isKill();
1770 unsigned IdxReg = MI->getOperand(1).getReg();
1771 bool IdxRegKill = MI->getOperand(1).isKill();
1773 // Scan backwards to find the instruction that defines the base
1774 // register. Due to post-RA scheduling, we can't count on it
1775 // immediately preceding the branch instruction.
1776 MachineBasicBlock::iterator PrevI = MI;
1777 MachineBasicBlock::iterator B = MBB->begin();
1778 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1781 // If for some reason we didn't find it, we can't do anything, so
1782 // just skip this one.
1783 if (!PrevI->definesRegister(BaseReg))
1786 MachineInstr *AddrMI = PrevI;
1788 // Examine the instruction that calculates the jumptable entry address.
1789 // Make sure it only defines the base register and kills any uses
1790 // other than the index register.
1791 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1792 const MachineOperand &MO = AddrMI->getOperand(k);
1793 if (!MO.isReg() || !MO.getReg())
1795 if (MO.isDef() && MO.getReg() != BaseReg) {
1799 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1807 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1808 // that gave us the initial base register definition.
1809 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1812 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1813 // to delete it as well.
1814 MachineInstr *LeaMI = PrevI;
1815 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1816 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1817 LeaMI->getOperand(0).getReg() != BaseReg)
1823 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1824 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1825 .addReg(IdxReg, getKillRegState(IdxRegKill))
1826 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1827 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1828 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1829 // is 2-byte aligned. For now, asm printer will fix it up.
1830 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1831 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1832 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1833 OrigSize += TII->GetInstSizeInBytes(MI);
1835 AddrMI->eraseFromParent();
1836 LeaMI->eraseFromParent();
1837 MI->eraseFromParent();
1839 int delta = OrigSize - NewSize;
1840 BBInfo[MBB->getNumber()].Size -= delta;
1841 AdjustBBOffsetsAfter(MBB);
1851 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1852 /// jump tables always branch forwards, since that's what tbb and tbh need.
1853 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1854 bool MadeChange = false;
1856 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1857 if (MJTI == 0) return false;
1859 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1860 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1861 MachineInstr *MI = T2JumpTables[i];
1862 const MCInstrDesc &MCID = MI->getDesc();
1863 unsigned NumOps = MCID.getNumOperands();
1864 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
1865 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1866 unsigned JTI = JTOP.getIndex();
1867 assert(JTI < JT.size());
1869 // We prefer if target blocks for the jump table come after the jump
1870 // instruction so we can use TB[BH]. Loop through the target blocks
1871 // and try to adjust them such that that's true.
1872 int JTNumber = MI->getParent()->getNumber();
1873 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1874 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1875 MachineBasicBlock *MBB = JTBBs[j];
1876 int DTNumber = MBB->getNumber();
1878 if (DTNumber < JTNumber) {
1879 // The destination precedes the switch. Try to move the block forward
1880 // so we have a positive offset.
1881 MachineBasicBlock *NewBB =
1882 AdjustJTTargetBlockForward(MBB, MI->getParent());
1884 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1893 MachineBasicBlock *ARMConstantIslands::
1894 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1896 MachineFunction &MF = *BB->getParent();
1898 // If the destination block is terminated by an unconditional branch,
1899 // try to move it; otherwise, create a new block following the jump
1900 // table that branches back to the actual target. This is a very simple
1901 // heuristic. FIXME: We can definitely improve it.
1902 MachineBasicBlock *TBB = 0, *FBB = 0;
1903 SmallVector<MachineOperand, 4> Cond;
1904 SmallVector<MachineOperand, 4> CondPrior;
1905 MachineFunction::iterator BBi = BB;
1906 MachineFunction::iterator OldPrior = prior(BBi);
1908 // If the block terminator isn't analyzable, don't try to move the block
1909 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1911 // If the block ends in an unconditional branch, move it. The prior block
1912 // has to have an analyzable terminator for us to move this one. Be paranoid
1913 // and make sure we're not trying to move the entry block of the function.
1914 if (!B && Cond.empty() && BB != MF.begin() &&
1915 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1916 BB->moveAfter(JTBB);
1917 OldPrior->updateTerminator();
1918 BB->updateTerminator();
1919 // Update numbering to account for the block being moved.
1920 MF.RenumberBlocks();
1925 // Create a new MBB for the code after the jump BB.
1926 MachineBasicBlock *NewBB =
1927 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1928 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1929 MF.insert(MBBI, NewBB);
1931 // Add an unconditional branch from NewBB to BB.
1932 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1933 // correspond directly to anything in the source.
1934 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1935 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1936 .addImm(ARMCC::AL).addReg(0);
1938 // Update internal data structures to account for the newly inserted MBB.
1939 MF.RenumberBlocks(NewBB);
1942 NewBB->addSuccessor(BB);
1943 JTBB->removeSuccessor(BB);
1944 JTBB->addSuccessor(NewBB);