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 //===----------------------------------------------------------------------===//
17 #include "ARMMachineFunctionInfo.h"
18 #include "MCTargetDesc/ARMAddressingModes.h"
19 #include "Thumb2InstrInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
38 #define DEBUG_TYPE "arm-cp-islands"
40 STATISTIC(NumCPEs, "Number of constpool entries");
41 STATISTIC(NumSplit, "Number of uncond branches inserted");
42 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
43 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
44 STATISTIC(NumTBs, "Number of table branches generated");
45 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
46 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
47 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
48 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
49 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
53 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
54 cl::desc("Adjust basic block layout to better use TB[BH]"));
56 // FIXME: This option should be removed once it has received sufficient testing.
58 AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
59 cl::desc("Align constant islands in code"));
61 /// UnknownPadding - Return the worst case padding that could result from
62 /// unknown offset bits. This does not include alignment padding caused by
63 /// known offset bits.
65 /// @param LogAlign log2(alignment)
66 /// @param KnownBits Number of known low offset bits.
67 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
68 if (KnownBits < LogAlign)
69 return (1u << LogAlign) - (1u << KnownBits);
74 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
75 /// requires constant pool entries to be scattered among the instructions
76 /// inside a function. To do this, it completely ignores the normal LLVM
77 /// constant pool; instead, it places constants wherever it feels like with
78 /// special instructions.
80 /// The terminology used in this pass includes:
81 /// Islands - Clumps of constants placed in the function.
82 /// Water - Potential places where an island could be formed.
83 /// CPE - A constant pool entry that has been placed somewhere, which
84 /// tracks a list of users.
85 class ARMConstantIslands : public MachineFunctionPass {
86 /// BasicBlockInfo - Information about the offset and size of a single
88 struct BasicBlockInfo {
89 /// Offset - Distance from the beginning of the function to the beginning
90 /// of this basic block.
92 /// Offsets are computed assuming worst case padding before an aligned
93 /// block. This means that subtracting basic block offsets always gives a
94 /// conservative estimate of the real distance which may be smaller.
96 /// Because worst case padding is used, the computed offset of an aligned
97 /// block may not actually be aligned.
100 /// Size - Size of the basic block in bytes. If the block contains
101 /// inline assembly, this is a worst case estimate.
103 /// The size does not include any alignment padding whether from the
104 /// beginning of the block, or from an aligned jump table at the end.
107 /// KnownBits - The number of low bits in Offset that are known to be
108 /// exact. The remaining bits of Offset are an upper bound.
111 /// Unalign - When non-zero, the block contains instructions (inline asm)
112 /// of unknown size. The real size may be smaller than Size bytes by a
113 /// multiple of 1 << Unalign.
116 /// PostAlign - When non-zero, the block terminator contains a .align
117 /// directive, so the end of the block is aligned to 1 << PostAlign
121 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
124 /// Compute the number of known offset bits internally to this block.
125 /// This number should be used to predict worst case padding when
126 /// splitting the block.
127 unsigned internalKnownBits() const {
128 unsigned Bits = Unalign ? Unalign : KnownBits;
129 // If the block size isn't a multiple of the known bits, assume the
130 // worst case padding.
131 if (Size & ((1u << Bits) - 1))
132 Bits = countTrailingZeros(Size);
136 /// Compute the offset immediately following this block. If LogAlign is
137 /// specified, return the offset the successor block will get if it has
139 unsigned postOffset(unsigned LogAlign = 0) const {
140 unsigned PO = Offset + Size;
141 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
144 // Add alignment padding from the terminator.
145 return PO + UnknownPadding(LA, internalKnownBits());
148 /// Compute the number of known low bits of postOffset. If this block
149 /// contains inline asm, the number of known bits drops to the
150 /// instruction alignment. An aligned terminator may increase the number
152 /// If LogAlign is given, also consider the alignment of the next block.
153 unsigned postKnownBits(unsigned LogAlign = 0) const {
154 return std::max(std::max(unsigned(PostAlign), LogAlign),
155 internalKnownBits());
159 std::vector<BasicBlockInfo> BBInfo;
161 /// WaterList - A sorted list of basic blocks where islands could be placed
162 /// (i.e. blocks that don't fall through to the following block, due
163 /// to a return, unreachable, or unconditional branch).
164 std::vector<MachineBasicBlock*> WaterList;
166 /// NewWaterList - The subset of WaterList that was created since the
167 /// previous iteration by inserting unconditional branches.
168 SmallSet<MachineBasicBlock*, 4> NewWaterList;
170 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
172 /// CPUser - One user of a constant pool, keeping the machine instruction
173 /// pointer, the constant pool being referenced, and the max displacement
174 /// allowed from the instruction to the CP. The HighWaterMark records the
175 /// highest basic block where a new CPEntry can be placed. To ensure this
176 /// pass terminates, the CP entries are initially placed at the end of the
177 /// function and then move monotonically to lower addresses. The
178 /// exception to this rule is when the current CP entry for a particular
179 /// CPUser is out of range, but there is another CP entry for the same
180 /// constant value in range. We want to use the existing in-range CP
181 /// entry, but if it later moves out of range, the search for new water
182 /// should resume where it left off. The HighWaterMark is used to record
187 MachineBasicBlock *HighWaterMark;
194 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
195 bool neg, bool soimm)
196 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
197 KnownAlignment(false) {
198 HighWaterMark = CPEMI->getParent();
200 /// getMaxDisp - Returns the maximum displacement supported by MI.
201 /// Correct for unknown alignment.
202 /// Conservatively subtract 2 bytes to handle weird alignment effects.
203 unsigned getMaxDisp() const {
204 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
208 /// CPUsers - Keep track of all of the machine instructions that use various
209 /// constant pools and their max displacement.
210 std::vector<CPUser> CPUsers;
212 /// CPEntry - One per constant pool entry, keeping the machine instruction
213 /// pointer, the constpool index, and the number of CPUser's which
214 /// reference this entry.
219 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
220 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
223 /// CPEntries - Keep track of all of the constant pool entry machine
224 /// instructions. For each original constpool index (i.e. those that
225 /// existed upon entry to this pass), it keeps a vector of entries.
226 /// Original elements are cloned as we go along; the clones are
227 /// put in the vector of the original element, but have distinct CPIs.
228 std::vector<std::vector<CPEntry> > CPEntries;
230 /// ImmBranch - One per immediate branch, keeping the machine instruction
231 /// pointer, conditional or unconditional, the max displacement,
232 /// and (if isCond is true) the corresponding unconditional branch
236 unsigned MaxDisp : 31;
239 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
240 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
243 /// ImmBranches - Keep track of all the immediate branch instructions.
245 std::vector<ImmBranch> ImmBranches;
247 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
249 SmallVector<MachineInstr*, 4> PushPopMIs;
251 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
252 SmallVector<MachineInstr*, 4> T2JumpTables;
254 /// HasFarJump - True if any far jump instruction has been emitted during
255 /// the branch fix up pass.
259 MachineConstantPool *MCP;
260 const ARMBaseInstrInfo *TII;
261 const ARMSubtarget *STI;
262 ARMFunctionInfo *AFI;
268 ARMConstantIslands() : MachineFunctionPass(ID) {}
270 bool runOnMachineFunction(MachineFunction &MF) override;
272 const char *getPassName() const override {
273 return "ARM constant island placement and branch shortening pass";
277 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
278 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
279 unsigned getCPELogAlign(const MachineInstr *CPEMI);
280 void scanFunctionJumpTables();
281 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
282 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
283 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
284 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
285 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
286 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
287 bool findAvailableWater(CPUser&U, unsigned UserOffset,
288 water_iterator &WaterIter);
289 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
290 MachineBasicBlock *&NewMBB);
291 bool handleConstantPoolUser(unsigned CPUserIndex);
292 void removeDeadCPEMI(MachineInstr *CPEMI);
293 bool removeUnusedCPEntries();
294 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
295 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
296 bool DoDump = false);
297 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
298 CPUser &U, unsigned &Growth);
299 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
300 bool fixupImmediateBr(ImmBranch &Br);
301 bool fixupConditionalBr(ImmBranch &Br);
302 bool fixupUnconditionalBr(ImmBranch &Br);
303 bool undoLRSpillRestore();
304 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
305 bool optimizeThumb2Instructions();
306 bool optimizeThumb2Branches();
307 bool reorderThumb2JumpTables();
308 bool optimizeThumb2JumpTables();
309 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
310 MachineBasicBlock *JTBB);
312 void computeBlockSize(MachineBasicBlock *MBB);
313 unsigned getOffsetOf(MachineInstr *MI) const;
314 unsigned getUserOffset(CPUser&) const;
318 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
319 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
320 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
322 return isOffsetInRange(UserOffset, TrialOffset,
323 U.getMaxDisp(), U.NegOk, U.IsSoImm);
326 char ARMConstantIslands::ID = 0;
329 /// verify - check BBOffsets, BBSizes, alignment of islands
330 void ARMConstantIslands::verify() {
332 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
334 MachineBasicBlock *MBB = MBBI;
335 unsigned MBBId = MBB->getNumber();
336 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
338 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
339 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
340 CPUser &U = CPUsers[i];
341 unsigned UserOffset = getUserOffset(U);
342 // Verify offset using the real max displacement without the safety
344 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
345 /* DoDump = */ true)) {
346 DEBUG(dbgs() << "OK\n");
349 DEBUG(dbgs() << "Out of range.\n");
352 llvm_unreachable("Constant pool entry out of range!");
357 /// print block size and offset information - debugging
358 void ARMConstantIslands::dumpBBs() {
360 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
361 const BasicBlockInfo &BBI = BBInfo[J];
362 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
363 << " kb=" << unsigned(BBI.KnownBits)
364 << " ua=" << unsigned(BBI.Unalign)
365 << " pa=" << unsigned(BBI.PostAlign)
366 << format(" size=%#x\n", BBInfo[J].Size);
371 /// createARMConstantIslandPass - returns an instance of the constpool
373 FunctionPass *llvm::createARMConstantIslandPass() {
374 return new ARMConstantIslands();
377 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
379 MCP = mf.getConstantPool();
381 DEBUG(dbgs() << "***** ARMConstantIslands: "
382 << MCP->getConstants().size() << " CP entries, aligned to "
383 << MCP->getConstantPoolAlignment() << " bytes *****\n");
385 TII = (const ARMBaseInstrInfo *)MF->getTarget()
388 AFI = MF->getInfo<ARMFunctionInfo>();
389 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
391 isThumb = AFI->isThumbFunction();
392 isThumb1 = AFI->isThumb1OnlyFunction();
393 isThumb2 = AFI->isThumb2Function();
397 // This pass invalidates liveness information when it splits basic blocks.
398 MF->getRegInfo().invalidateLiveness();
400 // Renumber all of the machine basic blocks in the function, guaranteeing that
401 // the numbers agree with the position of the block in the function.
402 MF->RenumberBlocks();
404 // Try to reorder and otherwise adjust the block layout to make good use
405 // of the TB[BH] instructions.
406 bool MadeChange = false;
407 if (isThumb2 && AdjustJumpTableBlocks) {
408 scanFunctionJumpTables();
409 MadeChange |= reorderThumb2JumpTables();
410 // Data is out of date, so clear it. It'll be re-computed later.
411 T2JumpTables.clear();
412 // Blocks may have shifted around. Keep the numbering up to date.
413 MF->RenumberBlocks();
416 // Thumb1 functions containing constant pools get 4-byte alignment.
417 // This is so we can keep exact track of where the alignment padding goes.
419 // ARM and Thumb2 functions need to be 4-byte aligned.
421 MF->ensureAlignment(2); // 2 = log2(4)
423 // Perform the initial placement of the constant pool entries. To start with,
424 // we put them all at the end of the function.
425 std::vector<MachineInstr*> CPEMIs;
427 doInitialPlacement(CPEMIs);
429 /// The next UID to take is the first unused one.
430 AFI->initPICLabelUId(CPEMIs.size());
432 // Do the initial scan of the function, building up information about the
433 // sizes of each block, the location of all the water, and finding all of the
434 // constant pool users.
435 initializeFunctionInfo(CPEMIs);
440 /// Remove dead constant pool entries.
441 MadeChange |= removeUnusedCPEntries();
443 // Iteratively place constant pool entries and fix up branches until there
445 unsigned NoCPIters = 0, NoBRIters = 0;
447 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
448 bool CPChange = false;
449 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
450 CPChange |= handleConstantPoolUser(i);
451 if (CPChange && ++NoCPIters > 30)
452 report_fatal_error("Constant Island pass failed to converge!");
455 // Clear NewWaterList now. If we split a block for branches, it should
456 // appear as "new water" for the next iteration of constant pool placement.
457 NewWaterList.clear();
459 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
460 bool BRChange = false;
461 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
462 BRChange |= fixupImmediateBr(ImmBranches[i]);
463 if (BRChange && ++NoBRIters > 30)
464 report_fatal_error("Branch Fix Up pass failed to converge!");
467 if (!CPChange && !BRChange)
472 // Shrink 32-bit Thumb2 branch, load, and store instructions.
473 if (isThumb2 && !STI->prefers32BitThumb())
474 MadeChange |= optimizeThumb2Instructions();
476 // After a while, this might be made debug-only, but it is not expensive.
479 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
480 // undo the spill / restore of LR if possible.
481 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
482 MadeChange |= undoLRSpillRestore();
484 // Save the mapping between original and cloned constpool entries.
485 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
486 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
487 const CPEntry & CPE = CPEntries[i][j];
488 AFI->recordCPEClone(i, CPE.CPI);
492 DEBUG(dbgs() << '\n'; dumpBBs());
500 T2JumpTables.clear();
505 /// doInitialPlacement - Perform the initial placement of the constant pool
506 /// entries. To start with, we put them all at the end of the function.
508 ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
509 // Create the basic block to hold the CPE's.
510 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
513 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
514 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
516 // Mark the basic block as required by the const-pool.
517 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
518 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
520 // The function needs to be as aligned as the basic blocks. The linker may
521 // move functions around based on their alignment.
522 MF->ensureAlignment(BB->getAlignment());
524 // Order the entries in BB by descending alignment. That ensures correct
525 // alignment of all entries as long as BB is sufficiently aligned. Keep
526 // track of the insertion point for each alignment. We are going to bucket
527 // sort the entries as they are created.
528 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
530 // Add all of the constants from the constant pool to the end block, use an
531 // identity mapping of CPI's to CPE's.
532 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
534 const DataLayout &TD = *MF->getSubtarget().getDataLayout();
535 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
536 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
537 assert(Size >= 4 && "Too small constant pool entry");
538 unsigned Align = CPs[i].getAlignment();
539 assert(isPowerOf2_32(Align) && "Invalid alignment");
540 // Verify that all constant pool entries are a multiple of their alignment.
541 // If not, we would have to pad them out so that instructions stay aligned.
542 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
544 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
545 unsigned LogAlign = Log2_32(Align);
546 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
547 MachineInstr *CPEMI =
548 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
549 .addImm(i).addConstantPoolIndex(i).addImm(Size);
550 CPEMIs.push_back(CPEMI);
552 // Ensure that future entries with higher alignment get inserted before
553 // CPEMI. This is bucket sort with iterators.
554 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
555 if (InsPoint[a] == InsAt)
558 // Add a new CPEntry, but no corresponding CPUser yet.
559 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
561 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
562 << Size << ", align = " << Align <<'\n');
567 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
568 /// into the block immediately after it.
569 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
570 // Get the next machine basic block in the function.
571 MachineFunction::iterator MBBI = MBB;
572 // Can't fall off end of function.
573 if (std::next(MBBI) == MBB->getParent()->end())
576 MachineBasicBlock *NextBB = std::next(MBBI);
577 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
578 E = MBB->succ_end(); I != E; ++I)
585 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
586 /// look up the corresponding CPEntry.
587 ARMConstantIslands::CPEntry
588 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
589 const MachineInstr *CPEMI) {
590 std::vector<CPEntry> &CPEs = CPEntries[CPI];
591 // Number of entries per constpool index should be small, just do a
593 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
594 if (CPEs[i].CPEMI == CPEMI)
600 /// getCPELogAlign - Returns the required alignment of the constant pool entry
601 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
602 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
603 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
605 // Everything is 4-byte aligned unless AlignConstantIslands is set.
606 if (!AlignConstantIslands)
609 unsigned CPI = CPEMI->getOperand(1).getIndex();
610 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
611 unsigned Align = MCP->getConstants()[CPI].getAlignment();
612 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
613 return Log2_32(Align);
616 /// scanFunctionJumpTables - Do a scan of the function, building up
617 /// information about the sizes of each block and the locations of all
619 void ARMConstantIslands::scanFunctionJumpTables() {
620 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
622 MachineBasicBlock &MBB = *MBBI;
624 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
626 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
627 T2JumpTables.push_back(I);
631 /// initializeFunctionInfo - Do the initial scan of the function, building up
632 /// information about the sizes of each block, the location of all the water,
633 /// and finding all of the constant pool users.
634 void ARMConstantIslands::
635 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
637 BBInfo.resize(MF->getNumBlockIDs());
639 // First thing, compute the size of all basic blocks, and see if the function
640 // has any inline assembly in it. If so, we have to be conservative about
641 // alignment assumptions, as we don't know for sure the size of any
642 // instructions in the inline assembly.
643 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
646 // The known bits of the entry block offset are determined by the function
648 BBInfo.front().KnownBits = MF->getAlignment();
650 // Compute block offsets and known bits.
651 adjustBBOffsetsAfter(MF->begin());
653 // Now go back through the instructions and build up our data structures.
654 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
656 MachineBasicBlock &MBB = *MBBI;
658 // If this block doesn't fall through into the next MBB, then this is
659 // 'water' that a constant pool island could be placed.
660 if (!BBHasFallthrough(&MBB))
661 WaterList.push_back(&MBB);
663 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
665 if (I->isDebugValue())
668 int Opc = I->getOpcode();
676 continue; // Ignore other JT branches
678 T2JumpTables.push_back(I);
679 continue; // Does not get an entry in ImmBranches
710 // Record this immediate branch.
711 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
712 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
715 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
716 PushPopMIs.push_back(I);
718 if (Opc == ARM::CONSTPOOL_ENTRY)
721 // Scan the instructions for constant pool operands.
722 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
723 if (I->getOperand(op).isCPI()) {
724 // We found one. The addressing mode tells us the max displacement
725 // from the PC that this instruction permits.
727 // Basic size info comes from the TSFlags field.
731 bool IsSoImm = false;
735 llvm_unreachable("Unknown addressing mode for CP reference!");
737 // Taking the address of a CP entry.
739 // This takes a SoImm, which is 8 bit immediate rotated. We'll
740 // pretend the maximum offset is 255 * 4. Since each instruction
741 // 4 byte wide, this is always correct. We'll check for other
742 // displacements that fits in a SoImm as well.
748 case ARM::t2LEApcrel:
761 Bits = 12; // +-offset_12
767 Scale = 4; // +(offset_8*4)
773 Scale = 4; // +-(offset_8*4)
778 // Remember that this is a user of a CP entry.
779 unsigned CPI = I->getOperand(op).getIndex();
780 MachineInstr *CPEMI = CPEMIs[CPI];
781 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
782 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
784 // Increment corresponding CPEntry reference count.
785 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
786 assert(CPE && "Cannot find a corresponding CPEntry!");
789 // Instructions can only use one CP entry, don't bother scanning the
790 // rest of the operands.
797 /// computeBlockSize - Compute the size and some alignment information for MBB.
798 /// This function updates BBInfo directly.
799 void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
800 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
805 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
807 BBI.Size += TII->GetInstSizeInBytes(I);
808 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
809 // The actual size may be smaller, but still a multiple of the instr size.
810 if (I->isInlineAsm())
811 BBI.Unalign = isThumb ? 1 : 2;
812 // Also consider instructions that may be shrunk later.
813 else if (isThumb && mayOptimizeThumb2Instruction(I))
817 // tBR_JTr contains a .align 2 directive.
818 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
820 MBB->getParent()->ensureAlignment(2);
824 /// getOffsetOf - Return the current offset of the specified machine instruction
825 /// from the start of the function. This offset changes as stuff is moved
826 /// around inside the function.
827 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
828 MachineBasicBlock *MBB = MI->getParent();
830 // The offset is composed of two things: the sum of the sizes of all MBB's
831 // before this instruction's block, and the offset from the start of the block
833 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
835 // Sum instructions before MI in MBB.
836 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
837 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
838 Offset += TII->GetInstSizeInBytes(I);
843 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
845 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
846 const MachineBasicBlock *RHS) {
847 return LHS->getNumber() < RHS->getNumber();
850 /// updateForInsertedWaterBlock - When a block is newly inserted into the
851 /// machine function, it upsets all of the block numbers. Renumber the blocks
852 /// and update the arrays that parallel this numbering.
853 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
854 // Renumber the MBB's to keep them consecutive.
855 NewBB->getParent()->RenumberBlocks(NewBB);
857 // Insert an entry into BBInfo to align it properly with the (newly
858 // renumbered) block numbers.
859 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
861 // Next, update WaterList. Specifically, we need to add NewMBB as having
862 // available water after it.
864 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
866 WaterList.insert(IP, NewBB);
870 /// Split the basic block containing MI into two blocks, which are joined by
871 /// an unconditional branch. Update data structures and renumber blocks to
872 /// account for this change and returns the newly created block.
873 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
874 MachineBasicBlock *OrigBB = MI->getParent();
876 // Create a new MBB for the code after the OrigBB.
877 MachineBasicBlock *NewBB =
878 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
879 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
880 MF->insert(MBBI, NewBB);
882 // Splice the instructions starting with MI over to NewBB.
883 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
885 // Add an unconditional branch from OrigBB to NewBB.
886 // Note the new unconditional branch is not being recorded.
887 // There doesn't seem to be meaningful DebugInfo available; this doesn't
888 // correspond to anything in the source.
889 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
891 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
893 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
894 .addImm(ARMCC::AL).addReg(0);
897 // Update the CFG. All succs of OrigBB are now succs of NewBB.
898 NewBB->transferSuccessors(OrigBB);
900 // OrigBB branches to NewBB.
901 OrigBB->addSuccessor(NewBB);
903 // Update internal data structures to account for the newly inserted MBB.
904 // This is almost the same as updateForInsertedWaterBlock, except that
905 // the Water goes after OrigBB, not NewBB.
906 MF->RenumberBlocks(NewBB);
908 // Insert an entry into BBInfo to align it properly with the (newly
909 // renumbered) block numbers.
910 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
912 // Next, update WaterList. Specifically, we need to add OrigMBB as having
913 // available water after it (but not if it's already there, which happens
914 // when splitting before a conditional branch that is followed by an
915 // unconditional branch - in that case we want to insert NewBB).
917 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
919 MachineBasicBlock* WaterBB = *IP;
920 if (WaterBB == OrigBB)
921 WaterList.insert(std::next(IP), NewBB);
923 WaterList.insert(IP, OrigBB);
924 NewWaterList.insert(OrigBB);
926 // Figure out how large the OrigBB is. As the first half of the original
927 // block, it cannot contain a tablejump. The size includes
928 // the new jump we added. (It should be possible to do this without
929 // recounting everything, but it's very confusing, and this is rarely
931 computeBlockSize(OrigBB);
933 // Figure out how large the NewMBB is. As the second half of the original
934 // block, it may contain a tablejump.
935 computeBlockSize(NewBB);
937 // All BBOffsets following these blocks must be modified.
938 adjustBBOffsetsAfter(OrigBB);
943 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
944 /// displacement computation. Update U.KnownAlignment to match its current
945 /// basic block location.
946 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
947 unsigned UserOffset = getOffsetOf(U.MI);
948 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
949 unsigned KnownBits = BBI.internalKnownBits();
951 // The value read from PC is offset from the actual instruction address.
952 UserOffset += (isThumb ? 4 : 8);
954 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
955 // Make sure U.getMaxDisp() returns a constrained range.
956 U.KnownAlignment = (KnownBits >= 2);
958 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
959 // purposes of the displacement computation; compensate for that here.
960 // For unknown alignments, getMaxDisp() constrains the range instead.
961 if (isThumb && U.KnownAlignment)
967 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
968 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
969 /// constant pool entry).
970 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
971 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
972 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
973 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
974 unsigned TrialOffset, unsigned MaxDisp,
975 bool NegativeOK, bool IsSoImm) {
976 if (UserOffset <= TrialOffset) {
977 // User before the Trial.
978 if (TrialOffset - UserOffset <= MaxDisp)
980 // FIXME: Make use full range of soimm values.
981 } else if (NegativeOK) {
982 if (UserOffset - TrialOffset <= MaxDisp)
984 // FIXME: Make use full range of soimm values.
989 /// isWaterInRange - Returns true if a CPE placed after the specified
990 /// Water (a basic block) will be in range for the specific MI.
992 /// Compute how much the function will grow by inserting a CPE after Water.
993 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
994 MachineBasicBlock* Water, CPUser &U,
996 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
997 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
998 unsigned NextBlockOffset, NextBlockAlignment;
999 MachineFunction::const_iterator NextBlock = Water;
1000 if (++NextBlock == MF->end()) {
1001 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1002 NextBlockAlignment = 0;
1004 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1005 NextBlockAlignment = NextBlock->getAlignment();
1007 unsigned Size = U.CPEMI->getOperand(2).getImm();
1008 unsigned CPEEnd = CPEOffset + Size;
1010 // The CPE may be able to hide in the alignment padding before the next
1011 // block. It may also cause more padding to be required if it is more aligned
1012 // that the next block.
1013 if (CPEEnd > NextBlockOffset) {
1014 Growth = CPEEnd - NextBlockOffset;
1015 // Compute the padding that would go at the end of the CPE to align the next
1017 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1019 // If the CPE is to be inserted before the instruction, that will raise
1020 // the offset of the instruction. Also account for unknown alignment padding
1021 // in blocks between CPE and the user.
1022 if (CPEOffset < UserOffset)
1023 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1025 // CPE fits in existing padding.
1028 return isOffsetInRange(UserOffset, CPEOffset, U);
1031 /// isCPEntryInRange - Returns true if the distance between specific MI and
1032 /// specific ConstPool entry instruction can fit in MI's displacement field.
1033 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1034 MachineInstr *CPEMI, unsigned MaxDisp,
1035 bool NegOk, bool DoDump) {
1036 unsigned CPEOffset = getOffsetOf(CPEMI);
1040 unsigned Block = MI->getParent()->getNumber();
1041 const BasicBlockInfo &BBI = BBInfo[Block];
1042 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1043 << " max delta=" << MaxDisp
1044 << format(" insn address=%#x", UserOffset)
1045 << " in BB#" << Block << ": "
1046 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1047 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1048 int(CPEOffset-UserOffset));
1052 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1056 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1057 /// unconditionally branches to its only successor.
1058 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1059 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1062 MachineBasicBlock *Succ = *MBB->succ_begin();
1063 MachineBasicBlock *Pred = *MBB->pred_begin();
1064 MachineInstr *PredMI = &Pred->back();
1065 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1066 || PredMI->getOpcode() == ARM::t2B)
1067 return PredMI->getOperand(0).getMBB() == Succ;
1072 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1073 unsigned BBNum = BB->getNumber();
1074 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1075 // Get the offset and known bits at the end of the layout predecessor.
1076 // Include the alignment of the current block.
1077 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1078 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1079 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1081 // This is where block i begins. Stop if the offset is already correct,
1082 // and we have updated 2 blocks. This is the maximum number of blocks
1083 // changed before calling this function.
1084 if (i > BBNum + 2 &&
1085 BBInfo[i].Offset == Offset &&
1086 BBInfo[i].KnownBits == KnownBits)
1089 BBInfo[i].Offset = Offset;
1090 BBInfo[i].KnownBits = KnownBits;
1094 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1095 /// and instruction CPEMI, and decrement its refcount. If the refcount
1096 /// becomes 0 remove the entry and instruction. Returns true if we removed
1097 /// the entry, false if we didn't.
1099 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1100 MachineInstr *CPEMI) {
1101 // Find the old entry. Eliminate it if it is no longer used.
1102 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1103 assert(CPE && "Unexpected!");
1104 if (--CPE->RefCount == 0) {
1105 removeDeadCPEMI(CPEMI);
1106 CPE->CPEMI = nullptr;
1113 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1114 /// if not, see if an in-range clone of the CPE is in range, and if so,
1115 /// change the data structures so the user references the clone. Returns:
1116 /// 0 = no existing entry found
1117 /// 1 = entry found, and there were no code insertions or deletions
1118 /// 2 = entry found, and there were code insertions or deletions
1119 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1121 MachineInstr *UserMI = U.MI;
1122 MachineInstr *CPEMI = U.CPEMI;
1124 // Check to see if the CPE is already in-range.
1125 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1127 DEBUG(dbgs() << "In range\n");
1131 // No. Look for previously created clones of the CPE that are in range.
1132 unsigned CPI = CPEMI->getOperand(1).getIndex();
1133 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1134 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1135 // We already tried this one
1136 if (CPEs[i].CPEMI == CPEMI)
1138 // Removing CPEs can leave empty entries, skip
1139 if (CPEs[i].CPEMI == nullptr)
1141 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1143 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1144 << CPEs[i].CPI << "\n");
1145 // Point the CPUser node to the replacement
1146 U.CPEMI = CPEs[i].CPEMI;
1147 // Change the CPI in the instruction operand to refer to the clone.
1148 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1149 if (UserMI->getOperand(j).isCPI()) {
1150 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1153 // Adjust the refcount of the clone...
1155 // ...and the original. If we didn't remove the old entry, none of the
1156 // addresses changed, so we don't need another pass.
1157 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1163 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1164 /// the specific unconditional branch instruction.
1165 static inline unsigned getUnconditionalBrDisp(int Opc) {
1168 return ((1<<10)-1)*2;
1170 return ((1<<23)-1)*2;
1175 return ((1<<23)-1)*4;
1178 /// findAvailableWater - Look for an existing entry in the WaterList in which
1179 /// we can place the CPE referenced from U so it's within range of U's MI.
1180 /// Returns true if found, false if not. If it returns true, WaterIter
1181 /// is set to the WaterList entry. For Thumb, prefer water that will not
1182 /// introduce padding to water that will. To ensure that this pass
1183 /// terminates, the CPE location for a particular CPUser is only allowed to
1184 /// move to a lower address, so search backward from the end of the list and
1185 /// prefer the first water that is in range.
1186 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1187 water_iterator &WaterIter) {
1188 if (WaterList.empty())
1191 unsigned BestGrowth = ~0u;
1192 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1194 MachineBasicBlock* WaterBB = *IP;
1195 // Check if water is in range and is either at a lower address than the
1196 // current "high water mark" or a new water block that was created since
1197 // the previous iteration by inserting an unconditional branch. In the
1198 // latter case, we want to allow resetting the high water mark back to
1199 // this new water since we haven't seen it before. Inserting branches
1200 // should be relatively uncommon and when it does happen, we want to be
1201 // sure to take advantage of it for all the CPEs near that block, so that
1202 // we don't insert more branches than necessary.
1204 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1205 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1206 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1207 // This is the least amount of required padding seen so far.
1208 BestGrowth = Growth;
1210 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1211 << " Growth=" << Growth << '\n');
1213 // Keep looking unless it is perfect.
1214 if (BestGrowth == 0)
1220 return BestGrowth != ~0u;
1223 /// createNewWater - No existing WaterList entry will work for
1224 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1225 /// block is used if in range, and the conditional branch munged so control
1226 /// flow is correct. Otherwise the block is split to create a hole with an
1227 /// unconditional branch around it. In either case NewMBB is set to a
1228 /// block following which the new island can be inserted (the WaterList
1229 /// is not adjusted).
1230 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1231 unsigned UserOffset,
1232 MachineBasicBlock *&NewMBB) {
1233 CPUser &U = CPUsers[CPUserIndex];
1234 MachineInstr *UserMI = U.MI;
1235 MachineInstr *CPEMI = U.CPEMI;
1236 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1237 MachineBasicBlock *UserMBB = UserMI->getParent();
1238 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1240 // If the block does not end in an unconditional branch already, and if the
1241 // end of the block is within range, make new water there. (The addition
1242 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1243 // Thumb2, 2 on Thumb1.
1244 if (BBHasFallthrough(UserMBB)) {
1245 // Size of branch to insert.
1246 unsigned Delta = isThumb1 ? 2 : 4;
1247 // Compute the offset where the CPE will begin.
1248 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1250 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1251 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1252 << format(", expected CPE offset %#x\n", CPEOffset));
1253 NewMBB = std::next(MachineFunction::iterator(UserMBB));
1254 // Add an unconditional branch from UserMBB to fallthrough block. Record
1255 // it for branch lengthening; this new branch will not get out of range,
1256 // but if the preceding conditional branch is out of range, the targets
1257 // will be exchanged, and the altered branch may be out of range, so the
1258 // machinery has to know about it.
1259 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1261 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1263 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1264 .addImm(ARMCC::AL).addReg(0);
1265 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1266 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1267 MaxDisp, false, UncondBr));
1268 BBInfo[UserMBB->getNumber()].Size += Delta;
1269 adjustBBOffsetsAfter(UserMBB);
1274 // What a big block. Find a place within the block to split it. This is a
1275 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1276 // entries are 4 bytes: if instruction I references island CPE, and
1277 // instruction I+1 references CPE', it will not work well to put CPE as far
1278 // forward as possible, since then CPE' cannot immediately follow it (that
1279 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1280 // need to create a new island. So, we make a first guess, then walk through
1281 // the instructions between the one currently being looked at and the
1282 // possible insertion point, and make sure any other instructions that
1283 // reference CPEs will be able to use the same island area; if not, we back
1284 // up the insertion point.
1286 // Try to split the block so it's fully aligned. Compute the latest split
1287 // point where we can add a 4-byte branch instruction, and then align to
1288 // LogAlign which is the largest possible alignment in the function.
1289 unsigned LogAlign = MF->getAlignment();
1290 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1291 unsigned KnownBits = UserBBI.internalKnownBits();
1292 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1293 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1294 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1297 // The 4 in the following is for the unconditional branch we'll be inserting
1298 // (allows for long branch on Thumb1). Alignment of the island is handled
1299 // inside isOffsetInRange.
1300 BaseInsertOffset -= 4;
1302 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1303 << " la=" << LogAlign
1304 << " kb=" << KnownBits
1305 << " up=" << UPad << '\n');
1307 // This could point off the end of the block if we've already got constant
1308 // pool entries following this block; only the last one is in the water list.
1309 // Back past any possible branches (allow for a conditional and a maximally
1310 // long unconditional).
1311 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1312 BaseInsertOffset = UserBBI.postOffset() - UPad - 8;
1313 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1315 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1316 CPEMI->getOperand(2).getImm();
1317 MachineBasicBlock::iterator MI = UserMI;
1319 unsigned CPUIndex = CPUserIndex+1;
1320 unsigned NumCPUsers = CPUsers.size();
1321 MachineInstr *LastIT = nullptr;
1322 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1323 Offset < BaseInsertOffset;
1324 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1325 assert(MI != UserMBB->end() && "Fell off end of block");
1326 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1327 CPUser &U = CPUsers[CPUIndex];
1328 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1329 // Shift intertion point by one unit of alignment so it is within reach.
1330 BaseInsertOffset -= 1u << LogAlign;
1331 EndInsertOffset -= 1u << LogAlign;
1333 // This is overly conservative, as we don't account for CPEMIs being
1334 // reused within the block, but it doesn't matter much. Also assume CPEs
1335 // are added in order with alignment padding. We may eventually be able
1336 // to pack the aligned CPEs better.
1337 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1341 // Remember the last IT instruction.
1342 if (MI->getOpcode() == ARM::t2IT)
1348 // Avoid splitting an IT block.
1350 unsigned PredReg = 0;
1351 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
1352 if (CC != ARMCC::AL)
1355 NewMBB = splitBlockBeforeInstr(MI);
1358 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1359 /// is out-of-range. If so, pick up the constant pool value and move it some
1360 /// place in-range. Return true if we changed any addresses (thus must run
1361 /// another pass of branch lengthening), false otherwise.
1362 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1363 CPUser &U = CPUsers[CPUserIndex];
1364 MachineInstr *UserMI = U.MI;
1365 MachineInstr *CPEMI = U.CPEMI;
1366 unsigned CPI = CPEMI->getOperand(1).getIndex();
1367 unsigned Size = CPEMI->getOperand(2).getImm();
1368 // Compute this only once, it's expensive.
1369 unsigned UserOffset = getUserOffset(U);
1371 // See if the current entry is within range, or there is a clone of it
1373 int result = findInRangeCPEntry(U, UserOffset);
1374 if (result==1) return false;
1375 else if (result==2) return true;
1377 // No existing clone of this CPE is within range.
1378 // We will be generating a new clone. Get a UID for it.
1379 unsigned ID = AFI->createPICLabelUId();
1381 // Look for water where we can place this CPE.
1382 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1383 MachineBasicBlock *NewMBB;
1385 if (findAvailableWater(U, UserOffset, IP)) {
1386 DEBUG(dbgs() << "Found water in range\n");
1387 MachineBasicBlock *WaterBB = *IP;
1389 // If the original WaterList entry was "new water" on this iteration,
1390 // propagate that to the new island. This is just keeping NewWaterList
1391 // updated to match the WaterList, which will be updated below.
1392 if (NewWaterList.erase(WaterBB))
1393 NewWaterList.insert(NewIsland);
1395 // The new CPE goes before the following block (NewMBB).
1396 NewMBB = std::next(MachineFunction::iterator(WaterBB));
1400 DEBUG(dbgs() << "No water found\n");
1401 createNewWater(CPUserIndex, UserOffset, NewMBB);
1403 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1404 // called while handling branches so that the water will be seen on the
1405 // next iteration for constant pools, but in this context, we don't want
1406 // it. Check for this so it will be removed from the WaterList.
1407 // Also remove any entry from NewWaterList.
1408 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1409 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1410 if (IP != WaterList.end())
1411 NewWaterList.erase(WaterBB);
1413 // We are adding new water. Update NewWaterList.
1414 NewWaterList.insert(NewIsland);
1417 // Remove the original WaterList entry; we want subsequent insertions in
1418 // this vicinity to go after the one we're about to insert. This
1419 // considerably reduces the number of times we have to move the same CPE
1420 // more than once and is also important to ensure the algorithm terminates.
1421 if (IP != WaterList.end())
1422 WaterList.erase(IP);
1424 // Okay, we know we can put an island before NewMBB now, do it!
1425 MF->insert(NewMBB, NewIsland);
1427 // Update internal data structures to account for the newly inserted MBB.
1428 updateForInsertedWaterBlock(NewIsland);
1430 // Decrement the old entry, and remove it if refcount becomes 0.
1431 decrementCPEReferenceCount(CPI, CPEMI);
1433 // Now that we have an island to add the CPE to, clone the original CPE and
1434 // add it to the island.
1435 U.HighWaterMark = NewIsland;
1436 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1437 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1438 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1441 // Mark the basic block as aligned as required by the const-pool entry.
1442 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1444 // Increase the size of the island block to account for the new entry.
1445 BBInfo[NewIsland->getNumber()].Size += Size;
1446 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1448 // Finally, change the CPI in the instruction operand to be ID.
1449 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1450 if (UserMI->getOperand(i).isCPI()) {
1451 UserMI->getOperand(i).setIndex(ID);
1455 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1456 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1461 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1462 /// sizes and offsets of impacted basic blocks.
1463 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1464 MachineBasicBlock *CPEBB = CPEMI->getParent();
1465 unsigned Size = CPEMI->getOperand(2).getImm();
1466 CPEMI->eraseFromParent();
1467 BBInfo[CPEBB->getNumber()].Size -= Size;
1468 // All succeeding offsets have the current size value added in, fix this.
1469 if (CPEBB->empty()) {
1470 BBInfo[CPEBB->getNumber()].Size = 0;
1472 // This block no longer needs to be aligned.
1473 CPEBB->setAlignment(0);
1475 // Entries are sorted by descending alignment, so realign from the front.
1476 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1478 adjustBBOffsetsAfter(CPEBB);
1479 // An island has only one predecessor BB and one successor BB. Check if
1480 // this BB's predecessor jumps directly to this BB's successor. This
1481 // shouldn't happen currently.
1482 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1483 // FIXME: remove the empty blocks after all the work is done?
1486 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1488 bool ARMConstantIslands::removeUnusedCPEntries() {
1489 unsigned MadeChange = false;
1490 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1491 std::vector<CPEntry> &CPEs = CPEntries[i];
1492 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1493 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1494 removeDeadCPEMI(CPEs[j].CPEMI);
1495 CPEs[j].CPEMI = nullptr;
1503 /// isBBInRange - Returns true if the distance between specific MI and
1504 /// specific BB can fit in MI's displacement field.
1505 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1507 unsigned PCAdj = isThumb ? 4 : 8;
1508 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1509 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1511 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1512 << " from BB#" << MI->getParent()->getNumber()
1513 << " max delta=" << MaxDisp
1514 << " from " << getOffsetOf(MI) << " to " << DestOffset
1515 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1517 if (BrOffset <= DestOffset) {
1518 // Branch before the Dest.
1519 if (DestOffset-BrOffset <= MaxDisp)
1522 if (BrOffset-DestOffset <= MaxDisp)
1528 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1529 /// away to fit in its displacement field.
1530 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1531 MachineInstr *MI = Br.MI;
1532 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1534 // Check to see if the DestBB is already in-range.
1535 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1539 return fixupUnconditionalBr(Br);
1540 return fixupConditionalBr(Br);
1543 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1544 /// too far away to fit in its displacement field. If the LR register has been
1545 /// spilled in the epilogue, then we can use BL to implement a far jump.
1546 /// Otherwise, add an intermediate branch instruction to a branch.
1548 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1549 MachineInstr *MI = Br.MI;
1550 MachineBasicBlock *MBB = MI->getParent();
1552 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1554 // Use BL to implement far jump.
1555 Br.MaxDisp = (1 << 21) * 2;
1556 MI->setDesc(TII->get(ARM::tBfar));
1557 BBInfo[MBB->getNumber()].Size += 2;
1558 adjustBBOffsetsAfter(MBB);
1562 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1567 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1568 /// far away to fit in its displacement field. It is converted to an inverse
1569 /// conditional branch + an unconditional branch to the destination.
1571 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1572 MachineInstr *MI = Br.MI;
1573 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1575 // Add an unconditional branch to the destination and invert the branch
1576 // condition to jump over it:
1582 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1583 CC = ARMCC::getOppositeCondition(CC);
1584 unsigned CCReg = MI->getOperand(2).getReg();
1586 // If the branch is at the end of its MBB and that has a fall-through block,
1587 // direct the updated conditional branch to the fall-through block. Otherwise,
1588 // split the MBB before the next instruction.
1589 MachineBasicBlock *MBB = MI->getParent();
1590 MachineInstr *BMI = &MBB->back();
1591 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1595 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1596 BMI->getOpcode() == Br.UncondBr) {
1597 // Last MI in the BB is an unconditional branch. Can we simply invert the
1598 // condition and swap destinations:
1604 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1605 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1606 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1608 BMI->getOperand(0).setMBB(DestBB);
1609 MI->getOperand(0).setMBB(NewDest);
1610 MI->getOperand(1).setImm(CC);
1617 splitBlockBeforeInstr(MI);
1618 // No need for the branch to the next block. We're adding an unconditional
1619 // branch to the destination.
1620 int delta = TII->GetInstSizeInBytes(&MBB->back());
1621 BBInfo[MBB->getNumber()].Size -= delta;
1622 MBB->back().eraseFromParent();
1623 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1625 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1627 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1628 << " also invert condition and change dest. to BB#"
1629 << NextBB->getNumber() << "\n");
1631 // Insert a new conditional branch and a new unconditional branch.
1632 // Also update the ImmBranch as well as adding a new entry for the new branch.
1633 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1634 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1635 Br.MI = &MBB->back();
1636 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1638 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1639 .addImm(ARMCC::AL).addReg(0);
1641 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1642 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1643 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1644 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1646 // Remove the old conditional branch. It may or may not still be in MBB.
1647 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1648 MI->eraseFromParent();
1649 adjustBBOffsetsAfter(MBB);
1653 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1654 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1655 /// to do this if tBfar is not used.
1656 bool ARMConstantIslands::undoLRSpillRestore() {
1657 bool MadeChange = false;
1658 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1659 MachineInstr *MI = PushPopMIs[i];
1660 // First two operands are predicates.
1661 if (MI->getOpcode() == ARM::tPOP_RET &&
1662 MI->getOperand(2).getReg() == ARM::PC &&
1663 MI->getNumExplicitOperands() == 3) {
1664 // Create the new insn and copy the predicate from the old.
1665 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1666 .addOperand(MI->getOperand(0))
1667 .addOperand(MI->getOperand(1));
1668 MI->eraseFromParent();
1675 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1676 // below may shrink MI.
1678 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1679 switch(MI->getOpcode()) {
1680 // optimizeThumb2Instructions.
1681 case ARM::t2LEApcrel:
1683 // optimizeThumb2Branches.
1687 // optimizeThumb2JumpTables.
1694 bool ARMConstantIslands::optimizeThumb2Instructions() {
1695 bool MadeChange = false;
1697 // Shrink ADR and LDR from constantpool.
1698 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1699 CPUser &U = CPUsers[i];
1700 unsigned Opcode = U.MI->getOpcode();
1701 unsigned NewOpc = 0;
1706 case ARM::t2LEApcrel:
1707 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1708 NewOpc = ARM::tLEApcrel;
1714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLDRpci;
1725 unsigned UserOffset = getUserOffset(U);
1726 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1728 // Be conservative with inline asm.
1729 if (!U.KnownAlignment)
1732 // FIXME: Check if offset is multiple of scale if scale is not 4.
1733 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1734 DEBUG(dbgs() << "Shrink: " << *U.MI);
1735 U.MI->setDesc(TII->get(NewOpc));
1736 MachineBasicBlock *MBB = U.MI->getParent();
1737 BBInfo[MBB->getNumber()].Size -= 2;
1738 adjustBBOffsetsAfter(MBB);
1744 MadeChange |= optimizeThumb2Branches();
1745 MadeChange |= optimizeThumb2JumpTables();
1749 bool ARMConstantIslands::optimizeThumb2Branches() {
1750 bool MadeChange = false;
1752 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1753 ImmBranch &Br = ImmBranches[i];
1754 unsigned Opcode = Br.MI->getOpcode();
1755 unsigned NewOpc = 0;
1773 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1774 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1775 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1776 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1777 Br.MI->setDesc(TII->get(NewOpc));
1778 MachineBasicBlock *MBB = Br.MI->getParent();
1779 BBInfo[MBB->getNumber()].Size -= 2;
1780 adjustBBOffsetsAfter(MBB);
1786 Opcode = Br.MI->getOpcode();
1787 if (Opcode != ARM::tBcc)
1790 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1791 // so this transformation is not safe.
1792 if (!Br.MI->killsRegister(ARM::CPSR))
1796 unsigned PredReg = 0;
1797 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
1798 if (Pred == ARMCC::EQ)
1800 else if (Pred == ARMCC::NE)
1801 NewOpc = ARM::tCBNZ;
1804 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1805 // Check if the distance is within 126. Subtract starting offset by 2
1806 // because the cmp will be eliminated.
1807 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1808 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1809 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1810 MachineBasicBlock::iterator CmpMI = Br.MI;
1811 if (CmpMI != Br.MI->getParent()->begin()) {
1813 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1814 unsigned Reg = CmpMI->getOperand(0).getReg();
1815 Pred = getInstrPredicate(CmpMI, PredReg);
1816 if (Pred == ARMCC::AL &&
1817 CmpMI->getOperand(1).getImm() == 0 &&
1818 isARMLowRegister(Reg)) {
1819 MachineBasicBlock *MBB = Br.MI->getParent();
1820 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1821 MachineInstr *NewBR =
1822 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1823 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1824 CmpMI->eraseFromParent();
1825 Br.MI->eraseFromParent();
1827 BBInfo[MBB->getNumber()].Size -= 2;
1828 adjustBBOffsetsAfter(MBB);
1840 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1841 /// jumptables when it's possible.
1842 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1843 bool MadeChange = false;
1845 // FIXME: After the tables are shrunk, can we get rid some of the
1846 // constantpool tables?
1847 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1848 if (!MJTI) return false;
1850 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1851 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1852 MachineInstr *MI = T2JumpTables[i];
1853 const MCInstrDesc &MCID = MI->getDesc();
1854 unsigned NumOps = MCID.getNumOperands();
1855 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1856 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1857 unsigned JTI = JTOP.getIndex();
1858 assert(JTI < JT.size());
1861 bool HalfWordOk = true;
1862 unsigned JTOffset = getOffsetOf(MI) + 4;
1863 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1864 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1865 MachineBasicBlock *MBB = JTBBs[j];
1866 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1867 // Negative offset is not ok. FIXME: We should change BB layout to make
1868 // sure all the branches are forward.
1869 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1871 unsigned TBHLimit = ((1<<16)-1)*2;
1872 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1874 if (!ByteOk && !HalfWordOk)
1878 if (ByteOk || HalfWordOk) {
1879 MachineBasicBlock *MBB = MI->getParent();
1880 unsigned BaseReg = MI->getOperand(0).getReg();
1881 bool BaseRegKill = MI->getOperand(0).isKill();
1884 unsigned IdxReg = MI->getOperand(1).getReg();
1885 bool IdxRegKill = MI->getOperand(1).isKill();
1887 // Scan backwards to find the instruction that defines the base
1888 // register. Due to post-RA scheduling, we can't count on it
1889 // immediately preceding the branch instruction.
1890 MachineBasicBlock::iterator PrevI = MI;
1891 MachineBasicBlock::iterator B = MBB->begin();
1892 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1895 // If for some reason we didn't find it, we can't do anything, so
1896 // just skip this one.
1897 if (!PrevI->definesRegister(BaseReg))
1900 MachineInstr *AddrMI = PrevI;
1902 // Examine the instruction that calculates the jumptable entry address.
1903 // Make sure it only defines the base register and kills any uses
1904 // other than the index register.
1905 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1906 const MachineOperand &MO = AddrMI->getOperand(k);
1907 if (!MO.isReg() || !MO.getReg())
1909 if (MO.isDef() && MO.getReg() != BaseReg) {
1913 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1921 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1922 // that gave us the initial base register definition.
1923 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1926 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1927 // to delete it as well.
1928 MachineInstr *LeaMI = PrevI;
1929 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1930 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1931 LeaMI->getOperand(0).getReg() != BaseReg)
1937 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1938 << " lea: " << *LeaMI);
1939 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1940 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1941 .addReg(IdxReg, getKillRegState(IdxRegKill))
1942 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1943 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1944 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1945 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1946 // is 2-byte aligned. For now, asm printer will fix it up.
1947 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1948 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1949 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1950 OrigSize += TII->GetInstSizeInBytes(MI);
1952 AddrMI->eraseFromParent();
1953 LeaMI->eraseFromParent();
1954 MI->eraseFromParent();
1956 int delta = OrigSize - NewSize;
1957 BBInfo[MBB->getNumber()].Size -= delta;
1958 adjustBBOffsetsAfter(MBB);
1968 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1969 /// jump tables always branch forwards, since that's what tbb and tbh need.
1970 bool ARMConstantIslands::reorderThumb2JumpTables() {
1971 bool MadeChange = false;
1973 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1974 if (!MJTI) return false;
1976 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1977 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1978 MachineInstr *MI = T2JumpTables[i];
1979 const MCInstrDesc &MCID = MI->getDesc();
1980 unsigned NumOps = MCID.getNumOperands();
1981 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1982 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1983 unsigned JTI = JTOP.getIndex();
1984 assert(JTI < JT.size());
1986 // We prefer if target blocks for the jump table come after the jump
1987 // instruction so we can use TB[BH]. Loop through the target blocks
1988 // and try to adjust them such that that's true.
1989 int JTNumber = MI->getParent()->getNumber();
1990 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1991 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1992 MachineBasicBlock *MBB = JTBBs[j];
1993 int DTNumber = MBB->getNumber();
1995 if (DTNumber < JTNumber) {
1996 // The destination precedes the switch. Try to move the block forward
1997 // so we have a positive offset.
1998 MachineBasicBlock *NewBB =
1999 adjustJTTargetBlockForward(MBB, MI->getParent());
2001 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2010 MachineBasicBlock *ARMConstantIslands::
2011 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2012 // If the destination block is terminated by an unconditional branch,
2013 // try to move it; otherwise, create a new block following the jump
2014 // table that branches back to the actual target. This is a very simple
2015 // heuristic. FIXME: We can definitely improve it.
2016 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2017 SmallVector<MachineOperand, 4> Cond;
2018 SmallVector<MachineOperand, 4> CondPrior;
2019 MachineFunction::iterator BBi = BB;
2020 MachineFunction::iterator OldPrior = std::prev(BBi);
2022 // If the block terminator isn't analyzable, don't try to move the block
2023 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2025 // If the block ends in an unconditional branch, move it. The prior block
2026 // has to have an analyzable terminator for us to move this one. Be paranoid
2027 // and make sure we're not trying to move the entry block of the function.
2028 if (!B && Cond.empty() && BB != MF->begin() &&
2029 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2030 BB->moveAfter(JTBB);
2031 OldPrior->updateTerminator();
2032 BB->updateTerminator();
2033 // Update numbering to account for the block being moved.
2034 MF->RenumberBlocks();
2039 // Create a new MBB for the code after the jump BB.
2040 MachineBasicBlock *NewBB =
2041 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2042 MachineFunction::iterator MBBI = JTBB; ++MBBI;
2043 MF->insert(MBBI, NewBB);
2045 // Add an unconditional branch from NewBB to BB.
2046 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2047 // correspond directly to anything in the source.
2048 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2049 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2050 .addImm(ARMCC::AL).addReg(0);
2052 // Update internal data structures to account for the newly inserted MBB.
2053 MF->RenumberBlocks(NewBB);
2056 NewBB->addSuccessor(BB);
2057 JTBB->removeSuccessor(BB);
2058 JTBB->addSuccessor(NewBB);