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 /// UnknownPadding - Return the worst case padding that could result from
57 /// unknown offset bits. This does not include alignment padding caused by
58 /// known offset bits.
60 /// @param LogAlign log2(alignment)
61 /// @param KnownBits Number of known low offset bits.
62 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
63 if (KnownBits < LogAlign)
64 return (1u << LogAlign) - (1u << KnownBits);
69 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
70 /// requires constant pool entries to be scattered among the instructions
71 /// inside a function. To do this, it completely ignores the normal LLVM
72 /// constant pool; instead, it places constants wherever it feels like with
73 /// special instructions.
75 /// The terminology used in this pass includes:
76 /// Islands - Clumps of constants placed in the function.
77 /// Water - Potential places where an island could be formed.
78 /// CPE - A constant pool entry that has been placed somewhere, which
79 /// tracks a list of users.
80 class ARMConstantIslands : public MachineFunctionPass {
81 /// BasicBlockInfo - Information about the offset and size of a single
83 struct BasicBlockInfo {
84 /// Offset - Distance from the beginning of the function to the beginning
85 /// of this basic block.
87 /// Offsets are computed assuming worst case padding before an aligned
88 /// block. This means that subtracting basic block offsets always gives a
89 /// conservative estimate of the real distance which may be smaller.
91 /// Because worst case padding is used, the computed offset of an aligned
92 /// block may not actually be aligned.
95 /// Size - Size of the basic block in bytes. If the block contains
96 /// inline assembly, this is a worst case estimate.
98 /// The size does not include any alignment padding whether from the
99 /// beginning of the block, or from an aligned jump table at the end.
102 /// KnownBits - The number of low bits in Offset that are known to be
103 /// exact. The remaining bits of Offset are an upper bound.
106 /// Unalign - When non-zero, the block contains instructions (inline asm)
107 /// of unknown size. The real size may be smaller than Size bytes by a
108 /// multiple of 1 << Unalign.
111 /// PostAlign - When non-zero, the block terminator contains a .align
112 /// directive, so the end of the block is aligned to 1 << PostAlign
116 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
119 /// Compute the number of known offset bits internally to this block.
120 /// This number should be used to predict worst case padding when
121 /// splitting the block.
122 unsigned internalKnownBits() const {
123 unsigned Bits = Unalign ? Unalign : KnownBits;
124 // If the block size isn't a multiple of the known bits, assume the
125 // worst case padding.
126 if (Size & ((1u << Bits) - 1))
127 Bits = countTrailingZeros(Size);
131 /// Compute the offset immediately following this block. If LogAlign is
132 /// specified, return the offset the successor block will get if it has
134 unsigned postOffset(unsigned LogAlign = 0) const {
135 unsigned PO = Offset + Size;
136 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
139 // Add alignment padding from the terminator.
140 return PO + UnknownPadding(LA, internalKnownBits());
143 /// Compute the number of known low bits of postOffset. If this block
144 /// contains inline asm, the number of known bits drops to the
145 /// instruction alignment. An aligned terminator may increase the number
147 /// If LogAlign is given, also consider the alignment of the next block.
148 unsigned postKnownBits(unsigned LogAlign = 0) const {
149 return std::max(std::max(unsigned(PostAlign), LogAlign),
150 internalKnownBits());
154 std::vector<BasicBlockInfo> BBInfo;
156 /// WaterList - A sorted list of basic blocks where islands could be placed
157 /// (i.e. blocks that don't fall through to the following block, due
158 /// to a return, unreachable, or unconditional branch).
159 std::vector<MachineBasicBlock*> WaterList;
161 /// NewWaterList - The subset of WaterList that was created since the
162 /// previous iteration by inserting unconditional branches.
163 SmallSet<MachineBasicBlock*, 4> NewWaterList;
165 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
167 /// CPUser - One user of a constant pool, keeping the machine instruction
168 /// pointer, the constant pool being referenced, and the max displacement
169 /// allowed from the instruction to the CP. The HighWaterMark records the
170 /// highest basic block where a new CPEntry can be placed. To ensure this
171 /// pass terminates, the CP entries are initially placed at the end of the
172 /// function and then move monotonically to lower addresses. The
173 /// exception to this rule is when the current CP entry for a particular
174 /// CPUser is out of range, but there is another CP entry for the same
175 /// constant value in range. We want to use the existing in-range CP
176 /// entry, but if it later moves out of range, the search for new water
177 /// should resume where it left off. The HighWaterMark is used to record
182 MachineBasicBlock *HighWaterMark;
189 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
190 bool neg, bool soimm)
191 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
192 KnownAlignment(false) {
193 HighWaterMark = CPEMI->getParent();
195 /// getMaxDisp - Returns the maximum displacement supported by MI.
196 /// Correct for unknown alignment.
197 /// Conservatively subtract 2 bytes to handle weird alignment effects.
198 unsigned getMaxDisp() const {
199 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
203 /// CPUsers - Keep track of all of the machine instructions that use various
204 /// constant pools and their max displacement.
205 std::vector<CPUser> CPUsers;
207 /// CPEntry - One per constant pool entry, keeping the machine instruction
208 /// pointer, the constpool index, and the number of CPUser's which
209 /// reference this entry.
214 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
215 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
218 /// CPEntries - Keep track of all of the constant pool entry machine
219 /// instructions. For each original constpool index (i.e. those that
220 /// existed upon entry to this pass), it keeps a vector of entries.
221 /// Original elements are cloned as we go along; the clones are
222 /// put in the vector of the original element, but have distinct CPIs.
223 std::vector<std::vector<CPEntry> > CPEntries;
225 /// ImmBranch - One per immediate branch, keeping the machine instruction
226 /// pointer, conditional or unconditional, the max displacement,
227 /// and (if isCond is true) the corresponding unconditional branch
231 unsigned MaxDisp : 31;
234 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
235 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
238 /// ImmBranches - Keep track of all the immediate branch instructions.
240 std::vector<ImmBranch> ImmBranches;
242 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
244 SmallVector<MachineInstr*, 4> PushPopMIs;
246 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
247 SmallVector<MachineInstr*, 4> T2JumpTables;
249 /// HasFarJump - True if any far jump instruction has been emitted during
250 /// the branch fix up pass.
254 MachineConstantPool *MCP;
255 const ARMBaseInstrInfo *TII;
256 const ARMSubtarget *STI;
257 ARMFunctionInfo *AFI;
263 ARMConstantIslands() : MachineFunctionPass(ID) {}
265 bool runOnMachineFunction(MachineFunction &MF) override;
267 const char *getPassName() const override {
268 return "ARM constant island placement and branch shortening pass";
272 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
273 bool BBHasFallthrough(MachineBasicBlock *MBB);
274 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
275 unsigned getCPELogAlign(const MachineInstr *CPEMI);
276 void scanFunctionJumpTables();
277 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
278 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
279 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
280 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
281 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
282 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
283 bool findAvailableWater(CPUser&U, unsigned UserOffset,
284 water_iterator &WaterIter);
285 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
286 MachineBasicBlock *&NewMBB);
287 bool handleConstantPoolUser(unsigned CPUserIndex);
288 void removeDeadCPEMI(MachineInstr *CPEMI);
289 bool removeUnusedCPEntries();
290 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
291 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
292 bool DoDump = false);
293 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
294 CPUser &U, unsigned &Growth);
295 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
296 bool fixupImmediateBr(ImmBranch &Br);
297 bool fixupConditionalBr(ImmBranch &Br);
298 bool fixupUnconditionalBr(ImmBranch &Br);
299 bool undoLRSpillRestore();
300 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
301 bool optimizeThumb2Instructions();
302 bool optimizeThumb2Branches();
303 bool reorderThumb2JumpTables();
304 unsigned removeDeadDefinitions(MachineInstr *MI, unsigned BaseReg,
306 bool optimizeThumb2JumpTables();
307 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
308 MachineBasicBlock *JTBB);
310 void computeBlockSize(MachineBasicBlock *MBB);
311 unsigned getOffsetOf(MachineInstr *MI) const;
312 unsigned getUserOffset(CPUser&) const;
316 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
317 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
318 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
320 return isOffsetInRange(UserOffset, TrialOffset,
321 U.getMaxDisp(), U.NegOk, U.IsSoImm);
324 char ARMConstantIslands::ID = 0;
327 /// verify - check BBOffsets, BBSizes, alignment of islands
328 void ARMConstantIslands::verify() {
330 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
332 MachineBasicBlock *MBB = MBBI;
333 unsigned MBBId = MBB->getNumber();
334 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
336 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
337 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
338 CPUser &U = CPUsers[i];
339 unsigned UserOffset = getUserOffset(U);
340 // Verify offset using the real max displacement without the safety
342 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
343 /* DoDump = */ true)) {
344 DEBUG(dbgs() << "OK\n");
347 DEBUG(dbgs() << "Out of range.\n");
350 llvm_unreachable("Constant pool entry out of range!");
355 /// print block size and offset information - debugging
356 void ARMConstantIslands::dumpBBs() {
358 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
359 const BasicBlockInfo &BBI = BBInfo[J];
360 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
361 << " kb=" << unsigned(BBI.KnownBits)
362 << " ua=" << unsigned(BBI.Unalign)
363 << " pa=" << unsigned(BBI.PostAlign)
364 << format(" size=%#x\n", BBInfo[J].Size);
369 /// createARMConstantIslandPass - returns an instance of the constpool
371 FunctionPass *llvm::createARMConstantIslandPass() {
372 return new ARMConstantIslands();
375 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
377 MCP = mf.getConstantPool();
379 DEBUG(dbgs() << "***** ARMConstantIslands: "
380 << MCP->getConstants().size() << " CP entries, aligned to "
381 << MCP->getConstantPoolAlignment() << " bytes *****\n");
383 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
384 TII = STI->getInstrInfo();
385 AFI = MF->getInfo<ARMFunctionInfo>();
387 isThumb = AFI->isThumbFunction();
388 isThumb1 = AFI->isThumb1OnlyFunction();
389 isThumb2 = AFI->isThumb2Function();
393 // This pass invalidates liveness information when it splits basic blocks.
394 MF->getRegInfo().invalidateLiveness();
396 // Renumber all of the machine basic blocks in the function, guaranteeing that
397 // the numbers agree with the position of the block in the function.
398 MF->RenumberBlocks();
400 // Try to reorder and otherwise adjust the block layout to make good use
401 // of the TB[BH] instructions.
402 bool MadeChange = false;
403 if (isThumb2 && AdjustJumpTableBlocks) {
404 scanFunctionJumpTables();
405 MadeChange |= reorderThumb2JumpTables();
406 // Data is out of date, so clear it. It'll be re-computed later.
407 T2JumpTables.clear();
408 // Blocks may have shifted around. Keep the numbering up to date.
409 MF->RenumberBlocks();
412 // Perform the initial placement of the constant pool entries. To start with,
413 // we put them all at the end of the function.
414 std::vector<MachineInstr*> CPEMIs;
416 doInitialPlacement(CPEMIs);
418 /// The next UID to take is the first unused one.
419 AFI->initPICLabelUId(CPEMIs.size());
421 // Do the initial scan of the function, building up information about the
422 // sizes of each block, the location of all the water, and finding all of the
423 // constant pool users.
424 initializeFunctionInfo(CPEMIs);
428 // Functions with jump tables need an alignment of 4 because they use the ADR
429 // instruction, which aligns the PC to 4 bytes before adding an offset.
430 if (!T2JumpTables.empty())
431 MF->ensureAlignment(2);
433 /// Remove dead constant pool entries.
434 MadeChange |= removeUnusedCPEntries();
436 // Iteratively place constant pool entries and fix up branches until there
438 unsigned NoCPIters = 0, NoBRIters = 0;
440 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
441 bool CPChange = false;
442 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
443 CPChange |= handleConstantPoolUser(i);
444 if (CPChange && ++NoCPIters > 30)
445 report_fatal_error("Constant Island pass failed to converge!");
448 // Clear NewWaterList now. If we split a block for branches, it should
449 // appear as "new water" for the next iteration of constant pool placement.
450 NewWaterList.clear();
452 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
453 bool BRChange = false;
454 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
455 BRChange |= fixupImmediateBr(ImmBranches[i]);
456 if (BRChange && ++NoBRIters > 30)
457 report_fatal_error("Branch Fix Up pass failed to converge!");
460 if (!CPChange && !BRChange)
465 // Shrink 32-bit Thumb2 branch, load, and store instructions.
466 if (isThumb2 && !STI->prefers32BitThumb())
467 MadeChange |= optimizeThumb2Instructions();
469 // After a while, this might be made debug-only, but it is not expensive.
472 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
473 // undo the spill / restore of LR if possible.
474 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
475 MadeChange |= undoLRSpillRestore();
477 // Save the mapping between original and cloned constpool entries.
478 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
479 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
480 const CPEntry & CPE = CPEntries[i][j];
481 AFI->recordCPEClone(i, CPE.CPI);
485 DEBUG(dbgs() << '\n'; dumpBBs());
493 T2JumpTables.clear();
498 /// doInitialPlacement - Perform the initial placement of the constant pool
499 /// entries. To start with, we put them all at the end of the function.
501 ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
502 // Create the basic block to hold the CPE's.
503 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
506 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
507 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
509 // Mark the basic block as required by the const-pool.
510 BB->setAlignment(MaxAlign);
512 // The function needs to be as aligned as the basic blocks. The linker may
513 // move functions around based on their alignment.
514 MF->ensureAlignment(BB->getAlignment());
516 // Order the entries in BB by descending alignment. That ensures correct
517 // alignment of all entries as long as BB is sufficiently aligned. Keep
518 // track of the insertion point for each alignment. We are going to bucket
519 // sort the entries as they are created.
520 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
522 // Add all of the constants from the constant pool to the end block, use an
523 // identity mapping of CPI's to CPE's.
524 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
526 const DataLayout &TD = *MF->getTarget().getDataLayout();
527 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
528 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
529 assert(Size >= 4 && "Too small constant pool entry");
530 unsigned Align = CPs[i].getAlignment();
531 assert(isPowerOf2_32(Align) && "Invalid alignment");
532 // Verify that all constant pool entries are a multiple of their alignment.
533 // If not, we would have to pad them out so that instructions stay aligned.
534 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
536 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
537 unsigned LogAlign = Log2_32(Align);
538 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
539 MachineInstr *CPEMI =
540 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
541 .addImm(i).addConstantPoolIndex(i).addImm(Size);
542 CPEMIs.push_back(CPEMI);
544 // Ensure that future entries with higher alignment get inserted before
545 // CPEMI. This is bucket sort with iterators.
546 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
547 if (InsPoint[a] == InsAt)
550 // Add a new CPEntry, but no corresponding CPUser yet.
551 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
553 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
554 << Size << ", align = " << Align <<'\n');
559 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
560 /// into the block immediately after it.
561 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
562 // Get the next machine basic block in the function.
563 MachineFunction::iterator MBBI = MBB;
564 // Can't fall off end of function.
565 if (std::next(MBBI) == MBB->getParent()->end())
568 MachineBasicBlock *NextBB = std::next(MBBI);
569 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
572 // Try to analyze the end of the block. A potential fallthrough may already
573 // have an unconditional branch for whatever reason.
574 MachineBasicBlock *TBB, *FBB;
575 SmallVector<MachineOperand, 4> Cond;
576 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
577 return TooDifficult || FBB == nullptr;
580 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
581 /// look up the corresponding CPEntry.
582 ARMConstantIslands::CPEntry
583 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
584 const MachineInstr *CPEMI) {
585 std::vector<CPEntry> &CPEs = CPEntries[CPI];
586 // Number of entries per constpool index should be small, just do a
588 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
589 if (CPEs[i].CPEMI == CPEMI)
595 /// getCPELogAlign - Returns the required alignment of the constant pool entry
596 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
597 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
598 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
600 unsigned CPI = CPEMI->getOperand(1).getIndex();
601 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
602 unsigned Align = MCP->getConstants()[CPI].getAlignment();
603 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
604 return Log2_32(Align);
607 /// scanFunctionJumpTables - Do a scan of the function, building up
608 /// information about the sizes of each block and the locations of all
610 void ARMConstantIslands::scanFunctionJumpTables() {
611 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
613 MachineBasicBlock &MBB = *MBBI;
615 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
617 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
618 T2JumpTables.push_back(I);
622 /// initializeFunctionInfo - Do the initial scan of the function, building up
623 /// information about the sizes of each block, the location of all the water,
624 /// and finding all of the constant pool users.
625 void ARMConstantIslands::
626 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
628 BBInfo.resize(MF->getNumBlockIDs());
630 // First thing, compute the size of all basic blocks, and see if the function
631 // has any inline assembly in it. If so, we have to be conservative about
632 // alignment assumptions, as we don't know for sure the size of any
633 // instructions in the inline assembly.
634 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
637 // The known bits of the entry block offset are determined by the function
639 BBInfo.front().KnownBits = MF->getAlignment();
641 // Compute block offsets and known bits.
642 adjustBBOffsetsAfter(MF->begin());
644 // Now go back through the instructions and build up our data structures.
645 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
647 MachineBasicBlock &MBB = *MBBI;
649 // If this block doesn't fall through into the next MBB, then this is
650 // 'water' that a constant pool island could be placed.
651 if (!BBHasFallthrough(&MBB))
652 WaterList.push_back(&MBB);
654 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
656 if (I->isDebugValue())
659 int Opc = I->getOpcode();
667 continue; // Ignore other JT branches
669 T2JumpTables.push_back(I);
670 continue; // Does not get an entry in ImmBranches
701 // Record this immediate branch.
702 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
703 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
706 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
707 PushPopMIs.push_back(I);
709 if (Opc == ARM::CONSTPOOL_ENTRY)
712 // Scan the instructions for constant pool operands.
713 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
714 if (I->getOperand(op).isCPI()) {
715 // We found one. The addressing mode tells us the max displacement
716 // from the PC that this instruction permits.
718 // Basic size info comes from the TSFlags field.
722 bool IsSoImm = false;
726 llvm_unreachable("Unknown addressing mode for CP reference!");
728 // Taking the address of a CP entry.
730 // This takes a SoImm, which is 8 bit immediate rotated. We'll
731 // pretend the maximum offset is 255 * 4. Since each instruction
732 // 4 byte wide, this is always correct. We'll check for other
733 // displacements that fits in a SoImm as well.
739 case ARM::t2LEApcrel:
752 Bits = 12; // +-offset_12
758 Scale = 4; // +(offset_8*4)
764 Scale = 4; // +-(offset_8*4)
769 // Remember that this is a user of a CP entry.
770 unsigned CPI = I->getOperand(op).getIndex();
771 MachineInstr *CPEMI = CPEMIs[CPI];
772 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
773 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
775 // Increment corresponding CPEntry reference count.
776 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
777 assert(CPE && "Cannot find a corresponding CPEntry!");
780 // Instructions can only use one CP entry, don't bother scanning the
781 // rest of the operands.
788 /// computeBlockSize - Compute the size and some alignment information for MBB.
789 /// This function updates BBInfo directly.
790 void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
791 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
796 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
798 BBI.Size += TII->GetInstSizeInBytes(I);
799 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
800 // The actual size may be smaller, but still a multiple of the instr size.
801 if (I->isInlineAsm())
802 BBI.Unalign = isThumb ? 1 : 2;
803 // Also consider instructions that may be shrunk later.
804 else if (isThumb && mayOptimizeThumb2Instruction(I))
808 // tBR_JTr contains a .align 2 directive.
809 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
811 MBB->getParent()->ensureAlignment(2);
815 /// getOffsetOf - Return the current offset of the specified machine instruction
816 /// from the start of the function. This offset changes as stuff is moved
817 /// around inside the function.
818 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
819 MachineBasicBlock *MBB = MI->getParent();
821 // The offset is composed of two things: the sum of the sizes of all MBB's
822 // before this instruction's block, and the offset from the start of the block
824 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
826 // Sum instructions before MI in MBB.
827 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
828 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
829 Offset += TII->GetInstSizeInBytes(I);
834 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
836 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
837 const MachineBasicBlock *RHS) {
838 return LHS->getNumber() < RHS->getNumber();
841 /// updateForInsertedWaterBlock - When a block is newly inserted into the
842 /// machine function, it upsets all of the block numbers. Renumber the blocks
843 /// and update the arrays that parallel this numbering.
844 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
845 // Renumber the MBB's to keep them consecutive.
846 NewBB->getParent()->RenumberBlocks(NewBB);
848 // Insert an entry into BBInfo to align it properly with the (newly
849 // renumbered) block numbers.
850 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
852 // Next, update WaterList. Specifically, we need to add NewMBB as having
853 // available water after it.
855 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
857 WaterList.insert(IP, NewBB);
861 /// Split the basic block containing MI into two blocks, which are joined by
862 /// an unconditional branch. Update data structures and renumber blocks to
863 /// account for this change and returns the newly created block.
864 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
865 MachineBasicBlock *OrigBB = MI->getParent();
867 // Create a new MBB for the code after the OrigBB.
868 MachineBasicBlock *NewBB =
869 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
870 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
871 MF->insert(MBBI, NewBB);
873 // Splice the instructions starting with MI over to NewBB.
874 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
876 // Add an unconditional branch from OrigBB to NewBB.
877 // Note the new unconditional branch is not being recorded.
878 // There doesn't seem to be meaningful DebugInfo available; this doesn't
879 // correspond to anything in the source.
880 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
882 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
884 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
885 .addImm(ARMCC::AL).addReg(0);
888 // Update the CFG. All succs of OrigBB are now succs of NewBB.
889 NewBB->transferSuccessors(OrigBB);
891 // OrigBB branches to NewBB.
892 OrigBB->addSuccessor(NewBB);
894 // Update internal data structures to account for the newly inserted MBB.
895 // This is almost the same as updateForInsertedWaterBlock, except that
896 // the Water goes after OrigBB, not NewBB.
897 MF->RenumberBlocks(NewBB);
899 // Insert an entry into BBInfo to align it properly with the (newly
900 // renumbered) block numbers.
901 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
903 // Next, update WaterList. Specifically, we need to add OrigMBB as having
904 // available water after it (but not if it's already there, which happens
905 // when splitting before a conditional branch that is followed by an
906 // unconditional branch - in that case we want to insert NewBB).
908 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
910 MachineBasicBlock* WaterBB = *IP;
911 if (WaterBB == OrigBB)
912 WaterList.insert(std::next(IP), NewBB);
914 WaterList.insert(IP, OrigBB);
915 NewWaterList.insert(OrigBB);
917 // Figure out how large the OrigBB is. As the first half of the original
918 // block, it cannot contain a tablejump. The size includes
919 // the new jump we added. (It should be possible to do this without
920 // recounting everything, but it's very confusing, and this is rarely
922 computeBlockSize(OrigBB);
924 // Figure out how large the NewMBB is. As the second half of the original
925 // block, it may contain a tablejump.
926 computeBlockSize(NewBB);
928 // All BBOffsets following these blocks must be modified.
929 adjustBBOffsetsAfter(OrigBB);
934 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
935 /// displacement computation. Update U.KnownAlignment to match its current
936 /// basic block location.
937 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
938 unsigned UserOffset = getOffsetOf(U.MI);
939 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
940 unsigned KnownBits = BBI.internalKnownBits();
942 // The value read from PC is offset from the actual instruction address.
943 UserOffset += (isThumb ? 4 : 8);
945 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
946 // Make sure U.getMaxDisp() returns a constrained range.
947 U.KnownAlignment = (KnownBits >= 2);
949 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
950 // purposes of the displacement computation; compensate for that here.
951 // For unknown alignments, getMaxDisp() constrains the range instead.
952 if (isThumb && U.KnownAlignment)
958 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
959 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
960 /// constant pool entry).
961 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
962 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
963 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
964 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
965 unsigned TrialOffset, unsigned MaxDisp,
966 bool NegativeOK, bool IsSoImm) {
967 if (UserOffset <= TrialOffset) {
968 // User before the Trial.
969 if (TrialOffset - UserOffset <= MaxDisp)
971 // FIXME: Make use full range of soimm values.
972 } else if (NegativeOK) {
973 if (UserOffset - TrialOffset <= MaxDisp)
975 // FIXME: Make use full range of soimm values.
980 /// isWaterInRange - Returns true if a CPE placed after the specified
981 /// Water (a basic block) will be in range for the specific MI.
983 /// Compute how much the function will grow by inserting a CPE after Water.
984 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
985 MachineBasicBlock* Water, CPUser &U,
987 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
988 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
989 unsigned NextBlockOffset, NextBlockAlignment;
990 MachineFunction::const_iterator NextBlock = Water;
991 if (++NextBlock == MF->end()) {
992 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
993 NextBlockAlignment = 0;
995 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
996 NextBlockAlignment = NextBlock->getAlignment();
998 unsigned Size = U.CPEMI->getOperand(2).getImm();
999 unsigned CPEEnd = CPEOffset + Size;
1001 // The CPE may be able to hide in the alignment padding before the next
1002 // block. It may also cause more padding to be required if it is more aligned
1003 // that the next block.
1004 if (CPEEnd > NextBlockOffset) {
1005 Growth = CPEEnd - NextBlockOffset;
1006 // Compute the padding that would go at the end of the CPE to align the next
1008 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1010 // If the CPE is to be inserted before the instruction, that will raise
1011 // the offset of the instruction. Also account for unknown alignment padding
1012 // in blocks between CPE and the user.
1013 if (CPEOffset < UserOffset)
1014 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1016 // CPE fits in existing padding.
1019 return isOffsetInRange(UserOffset, CPEOffset, U);
1022 /// isCPEntryInRange - Returns true if the distance between specific MI and
1023 /// specific ConstPool entry instruction can fit in MI's displacement field.
1024 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1025 MachineInstr *CPEMI, unsigned MaxDisp,
1026 bool NegOk, bool DoDump) {
1027 unsigned CPEOffset = getOffsetOf(CPEMI);
1031 unsigned Block = MI->getParent()->getNumber();
1032 const BasicBlockInfo &BBI = BBInfo[Block];
1033 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1034 << " max delta=" << MaxDisp
1035 << format(" insn address=%#x", UserOffset)
1036 << " in BB#" << Block << ": "
1037 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1038 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1039 int(CPEOffset-UserOffset));
1043 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1047 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1048 /// unconditionally branches to its only successor.
1049 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1050 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1053 MachineBasicBlock *Succ = *MBB->succ_begin();
1054 MachineBasicBlock *Pred = *MBB->pred_begin();
1055 MachineInstr *PredMI = &Pred->back();
1056 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1057 || PredMI->getOpcode() == ARM::t2B)
1058 return PredMI->getOperand(0).getMBB() == Succ;
1063 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1064 unsigned BBNum = BB->getNumber();
1065 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1066 // Get the offset and known bits at the end of the layout predecessor.
1067 // Include the alignment of the current block.
1068 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1069 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1070 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1072 // This is where block i begins. Stop if the offset is already correct,
1073 // and we have updated 2 blocks. This is the maximum number of blocks
1074 // changed before calling this function.
1075 if (i > BBNum + 2 &&
1076 BBInfo[i].Offset == Offset &&
1077 BBInfo[i].KnownBits == KnownBits)
1080 BBInfo[i].Offset = Offset;
1081 BBInfo[i].KnownBits = KnownBits;
1085 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1086 /// and instruction CPEMI, and decrement its refcount. If the refcount
1087 /// becomes 0 remove the entry and instruction. Returns true if we removed
1088 /// the entry, false if we didn't.
1090 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1091 MachineInstr *CPEMI) {
1092 // Find the old entry. Eliminate it if it is no longer used.
1093 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1094 assert(CPE && "Unexpected!");
1095 if (--CPE->RefCount == 0) {
1096 removeDeadCPEMI(CPEMI);
1097 CPE->CPEMI = nullptr;
1104 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1105 /// if not, see if an in-range clone of the CPE is in range, and if so,
1106 /// change the data structures so the user references the clone. Returns:
1107 /// 0 = no existing entry found
1108 /// 1 = entry found, and there were no code insertions or deletions
1109 /// 2 = entry found, and there were code insertions or deletions
1110 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1112 MachineInstr *UserMI = U.MI;
1113 MachineInstr *CPEMI = U.CPEMI;
1115 // Check to see if the CPE is already in-range.
1116 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1118 DEBUG(dbgs() << "In range\n");
1122 // No. Look for previously created clones of the CPE that are in range.
1123 unsigned CPI = CPEMI->getOperand(1).getIndex();
1124 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1125 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1126 // We already tried this one
1127 if (CPEs[i].CPEMI == CPEMI)
1129 // Removing CPEs can leave empty entries, skip
1130 if (CPEs[i].CPEMI == nullptr)
1132 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1134 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1135 << CPEs[i].CPI << "\n");
1136 // Point the CPUser node to the replacement
1137 U.CPEMI = CPEs[i].CPEMI;
1138 // Change the CPI in the instruction operand to refer to the clone.
1139 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1140 if (UserMI->getOperand(j).isCPI()) {
1141 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1144 // Adjust the refcount of the clone...
1146 // ...and the original. If we didn't remove the old entry, none of the
1147 // addresses changed, so we don't need another pass.
1148 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1154 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1155 /// the specific unconditional branch instruction.
1156 static inline unsigned getUnconditionalBrDisp(int Opc) {
1159 return ((1<<10)-1)*2;
1161 return ((1<<23)-1)*2;
1166 return ((1<<23)-1)*4;
1169 /// findAvailableWater - Look for an existing entry in the WaterList in which
1170 /// we can place the CPE referenced from U so it's within range of U's MI.
1171 /// Returns true if found, false if not. If it returns true, WaterIter
1172 /// is set to the WaterList entry. For Thumb, prefer water that will not
1173 /// introduce padding to water that will. To ensure that this pass
1174 /// terminates, the CPE location for a particular CPUser is only allowed to
1175 /// move to a lower address, so search backward from the end of the list and
1176 /// prefer the first water that is in range.
1177 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1178 water_iterator &WaterIter) {
1179 if (WaterList.empty())
1182 unsigned BestGrowth = ~0u;
1183 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1185 MachineBasicBlock* WaterBB = *IP;
1186 // Check if water is in range and is either at a lower address than the
1187 // current "high water mark" or a new water block that was created since
1188 // the previous iteration by inserting an unconditional branch. In the
1189 // latter case, we want to allow resetting the high water mark back to
1190 // this new water since we haven't seen it before. Inserting branches
1191 // should be relatively uncommon and when it does happen, we want to be
1192 // sure to take advantage of it for all the CPEs near that block, so that
1193 // we don't insert more branches than necessary.
1195 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1196 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1197 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1198 Growth < BestGrowth) {
1199 // This is the least amount of required padding seen so far.
1200 BestGrowth = Growth;
1202 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1203 << " Growth=" << Growth << '\n');
1205 // Keep looking unless it is perfect.
1206 if (BestGrowth == 0)
1212 return BestGrowth != ~0u;
1215 /// createNewWater - No existing WaterList entry will work for
1216 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1217 /// block is used if in range, and the conditional branch munged so control
1218 /// flow is correct. Otherwise the block is split to create a hole with an
1219 /// unconditional branch around it. In either case NewMBB is set to a
1220 /// block following which the new island can be inserted (the WaterList
1221 /// is not adjusted).
1222 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1223 unsigned UserOffset,
1224 MachineBasicBlock *&NewMBB) {
1225 CPUser &U = CPUsers[CPUserIndex];
1226 MachineInstr *UserMI = U.MI;
1227 MachineInstr *CPEMI = U.CPEMI;
1228 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1229 MachineBasicBlock *UserMBB = UserMI->getParent();
1230 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1232 // If the block does not end in an unconditional branch already, and if the
1233 // end of the block is within range, make new water there. (The addition
1234 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1235 // Thumb2, 2 on Thumb1.
1236 if (BBHasFallthrough(UserMBB)) {
1237 // Size of branch to insert.
1238 unsigned Delta = isThumb1 ? 2 : 4;
1239 // Compute the offset where the CPE will begin.
1240 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1242 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1243 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1244 << format(", expected CPE offset %#x\n", CPEOffset));
1245 NewMBB = std::next(MachineFunction::iterator(UserMBB));
1246 // Add an unconditional branch from UserMBB to fallthrough block. Record
1247 // it for branch lengthening; this new branch will not get out of range,
1248 // but if the preceding conditional branch is out of range, the targets
1249 // will be exchanged, and the altered branch may be out of range, so the
1250 // machinery has to know about it.
1251 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1253 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1255 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1256 .addImm(ARMCC::AL).addReg(0);
1257 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1258 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1259 MaxDisp, false, UncondBr));
1260 computeBlockSize(UserMBB);
1261 adjustBBOffsetsAfter(UserMBB);
1266 // What a big block. Find a place within the block to split it. This is a
1267 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1268 // entries are 4 bytes: if instruction I references island CPE, and
1269 // instruction I+1 references CPE', it will not work well to put CPE as far
1270 // forward as possible, since then CPE' cannot immediately follow it (that
1271 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1272 // need to create a new island. So, we make a first guess, then walk through
1273 // the instructions between the one currently being looked at and the
1274 // possible insertion point, and make sure any other instructions that
1275 // reference CPEs will be able to use the same island area; if not, we back
1276 // up the insertion point.
1278 // Try to split the block so it's fully aligned. Compute the latest split
1279 // point where we can add a 4-byte branch instruction, and then align to
1280 // LogAlign which is the largest possible alignment in the function.
1281 unsigned LogAlign = MF->getAlignment();
1282 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1283 unsigned KnownBits = UserBBI.internalKnownBits();
1284 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1285 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1286 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1289 // The 4 in the following is for the unconditional branch we'll be inserting
1290 // (allows for long branch on Thumb1). Alignment of the island is handled
1291 // inside isOffsetInRange.
1292 BaseInsertOffset -= 4;
1294 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1295 << " la=" << LogAlign
1296 << " kb=" << KnownBits
1297 << " up=" << UPad << '\n');
1299 // This could point off the end of the block if we've already got constant
1300 // pool entries following this block; only the last one is in the water list.
1301 // Back past any possible branches (allow for a conditional and a maximally
1302 // long unconditional).
1303 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1304 // Ensure BaseInsertOffset is larger than the offset of the instruction
1305 // following UserMI so that the loop which searches for the split point
1306 // iterates at least once.
1308 std::max(UserBBI.postOffset() - UPad - 8,
1309 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
1310 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1312 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1313 CPEMI->getOperand(2).getImm();
1314 MachineBasicBlock::iterator MI = UserMI;
1316 unsigned CPUIndex = CPUserIndex+1;
1317 unsigned NumCPUsers = CPUsers.size();
1318 MachineInstr *LastIT = nullptr;
1319 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1320 Offset < BaseInsertOffset;
1321 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1322 assert(MI != UserMBB->end() && "Fell off end of block");
1323 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1324 CPUser &U = CPUsers[CPUIndex];
1325 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1326 // Shift intertion point by one unit of alignment so it is within reach.
1327 BaseInsertOffset -= 1u << LogAlign;
1328 EndInsertOffset -= 1u << LogAlign;
1330 // This is overly conservative, as we don't account for CPEMIs being
1331 // reused within the block, but it doesn't matter much. Also assume CPEs
1332 // are added in order with alignment padding. We may eventually be able
1333 // to pack the aligned CPEs better.
1334 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1338 // Remember the last IT instruction.
1339 if (MI->getOpcode() == ARM::t2IT)
1345 // Avoid splitting an IT block.
1347 unsigned PredReg = 0;
1348 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
1349 if (CC != ARMCC::AL)
1353 // We really must not split an IT block.
1354 DEBUG(unsigned PredReg;
1355 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1357 NewMBB = splitBlockBeforeInstr(MI);
1360 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1361 /// is out-of-range. If so, pick up the constant pool value and move it some
1362 /// place in-range. Return true if we changed any addresses (thus must run
1363 /// another pass of branch lengthening), false otherwise.
1364 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1365 CPUser &U = CPUsers[CPUserIndex];
1366 MachineInstr *UserMI = U.MI;
1367 MachineInstr *CPEMI = U.CPEMI;
1368 unsigned CPI = CPEMI->getOperand(1).getIndex();
1369 unsigned Size = CPEMI->getOperand(2).getImm();
1370 // Compute this only once, it's expensive.
1371 unsigned UserOffset = getUserOffset(U);
1373 // See if the current entry is within range, or there is a clone of it
1375 int result = findInRangeCPEntry(U, UserOffset);
1376 if (result==1) return false;
1377 else if (result==2) return true;
1379 // No existing clone of this CPE is within range.
1380 // We will be generating a new clone. Get a UID for it.
1381 unsigned ID = AFI->createPICLabelUId();
1383 // Look for water where we can place this CPE.
1384 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1385 MachineBasicBlock *NewMBB;
1387 if (findAvailableWater(U, UserOffset, IP)) {
1388 DEBUG(dbgs() << "Found water in range\n");
1389 MachineBasicBlock *WaterBB = *IP;
1391 // If the original WaterList entry was "new water" on this iteration,
1392 // propagate that to the new island. This is just keeping NewWaterList
1393 // updated to match the WaterList, which will be updated below.
1394 if (NewWaterList.erase(WaterBB))
1395 NewWaterList.insert(NewIsland);
1397 // The new CPE goes before the following block (NewMBB).
1398 NewMBB = std::next(MachineFunction::iterator(WaterBB));
1402 DEBUG(dbgs() << "No water found\n");
1403 createNewWater(CPUserIndex, UserOffset, NewMBB);
1405 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1406 // called while handling branches so that the water will be seen on the
1407 // next iteration for constant pools, but in this context, we don't want
1408 // it. Check for this so it will be removed from the WaterList.
1409 // Also remove any entry from NewWaterList.
1410 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1411 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1412 if (IP != WaterList.end())
1413 NewWaterList.erase(WaterBB);
1415 // We are adding new water. Update NewWaterList.
1416 NewWaterList.insert(NewIsland);
1419 // Remove the original WaterList entry; we want subsequent insertions in
1420 // this vicinity to go after the one we're about to insert. This
1421 // considerably reduces the number of times we have to move the same CPE
1422 // more than once and is also important to ensure the algorithm terminates.
1423 if (IP != WaterList.end())
1424 WaterList.erase(IP);
1426 // Okay, we know we can put an island before NewMBB now, do it!
1427 MF->insert(NewMBB, NewIsland);
1429 // Update internal data structures to account for the newly inserted MBB.
1430 updateForInsertedWaterBlock(NewIsland);
1432 // Decrement the old entry, and remove it if refcount becomes 0.
1433 decrementCPEReferenceCount(CPI, CPEMI);
1435 // Now that we have an island to add the CPE to, clone the original CPE and
1436 // add it to the island.
1437 U.HighWaterMark = NewIsland;
1438 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1439 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1440 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1443 // Mark the basic block as aligned as required by the const-pool entry.
1444 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1446 // Increase the size of the island block to account for the new entry.
1447 BBInfo[NewIsland->getNumber()].Size += Size;
1448 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1450 // Finally, change the CPI in the instruction operand to be ID.
1451 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1452 if (UserMI->getOperand(i).isCPI()) {
1453 UserMI->getOperand(i).setIndex(ID);
1457 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1458 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1463 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1464 /// sizes and offsets of impacted basic blocks.
1465 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1466 MachineBasicBlock *CPEBB = CPEMI->getParent();
1467 unsigned Size = CPEMI->getOperand(2).getImm();
1468 CPEMI->eraseFromParent();
1469 BBInfo[CPEBB->getNumber()].Size -= Size;
1470 // All succeeding offsets have the current size value added in, fix this.
1471 if (CPEBB->empty()) {
1472 BBInfo[CPEBB->getNumber()].Size = 0;
1474 // This block no longer needs to be aligned.
1475 CPEBB->setAlignment(0);
1477 // Entries are sorted by descending alignment, so realign from the front.
1478 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1480 adjustBBOffsetsAfter(CPEBB);
1481 // An island has only one predecessor BB and one successor BB. Check if
1482 // this BB's predecessor jumps directly to this BB's successor. This
1483 // shouldn't happen currently.
1484 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1485 // FIXME: remove the empty blocks after all the work is done?
1488 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1490 bool ARMConstantIslands::removeUnusedCPEntries() {
1491 unsigned MadeChange = false;
1492 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1493 std::vector<CPEntry> &CPEs = CPEntries[i];
1494 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1495 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1496 removeDeadCPEMI(CPEs[j].CPEMI);
1497 CPEs[j].CPEMI = nullptr;
1505 /// isBBInRange - Returns true if the distance between specific MI and
1506 /// specific BB can fit in MI's displacement field.
1507 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1509 unsigned PCAdj = isThumb ? 4 : 8;
1510 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1511 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1513 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1514 << " from BB#" << MI->getParent()->getNumber()
1515 << " max delta=" << MaxDisp
1516 << " from " << getOffsetOf(MI) << " to " << DestOffset
1517 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1519 if (BrOffset <= DestOffset) {
1520 // Branch before the Dest.
1521 if (DestOffset-BrOffset <= MaxDisp)
1524 if (BrOffset-DestOffset <= MaxDisp)
1530 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1531 /// away to fit in its displacement field.
1532 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1533 MachineInstr *MI = Br.MI;
1534 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1536 // Check to see if the DestBB is already in-range.
1537 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1541 return fixupUnconditionalBr(Br);
1542 return fixupConditionalBr(Br);
1545 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1546 /// too far away to fit in its displacement field. If the LR register has been
1547 /// spilled in the epilogue, then we can use BL to implement a far jump.
1548 /// Otherwise, add an intermediate branch instruction to a branch.
1550 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1551 MachineInstr *MI = Br.MI;
1552 MachineBasicBlock *MBB = MI->getParent();
1554 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1556 // Use BL to implement far jump.
1557 Br.MaxDisp = (1 << 21) * 2;
1558 MI->setDesc(TII->get(ARM::tBfar));
1559 BBInfo[MBB->getNumber()].Size += 2;
1560 adjustBBOffsetsAfter(MBB);
1564 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1569 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1570 /// far away to fit in its displacement field. It is converted to an inverse
1571 /// conditional branch + an unconditional branch to the destination.
1573 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1574 MachineInstr *MI = Br.MI;
1575 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1577 // Add an unconditional branch to the destination and invert the branch
1578 // condition to jump over it:
1584 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1585 CC = ARMCC::getOppositeCondition(CC);
1586 unsigned CCReg = MI->getOperand(2).getReg();
1588 // If the branch is at the end of its MBB and that has a fall-through block,
1589 // direct the updated conditional branch to the fall-through block. Otherwise,
1590 // split the MBB before the next instruction.
1591 MachineBasicBlock *MBB = MI->getParent();
1592 MachineInstr *BMI = &MBB->back();
1593 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1597 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1598 BMI->getOpcode() == Br.UncondBr) {
1599 // Last MI in the BB is an unconditional branch. Can we simply invert the
1600 // condition and swap destinations:
1606 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1607 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1608 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1610 BMI->getOperand(0).setMBB(DestBB);
1611 MI->getOperand(0).setMBB(NewDest);
1612 MI->getOperand(1).setImm(CC);
1619 splitBlockBeforeInstr(MI);
1620 // No need for the branch to the next block. We're adding an unconditional
1621 // branch to the destination.
1622 int delta = TII->GetInstSizeInBytes(&MBB->back());
1623 BBInfo[MBB->getNumber()].Size -= delta;
1624 MBB->back().eraseFromParent();
1625 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1627 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1629 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1630 << " also invert condition and change dest. to BB#"
1631 << NextBB->getNumber() << "\n");
1633 // Insert a new conditional branch and a new unconditional branch.
1634 // Also update the ImmBranch as well as adding a new entry for the new branch.
1635 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1636 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1637 Br.MI = &MBB->back();
1638 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1640 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1641 .addImm(ARMCC::AL).addReg(0);
1643 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1644 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1645 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1646 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1648 // Remove the old conditional branch. It may or may not still be in MBB.
1649 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1650 MI->eraseFromParent();
1651 adjustBBOffsetsAfter(MBB);
1655 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1656 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1657 /// to do this if tBfar is not used.
1658 bool ARMConstantIslands::undoLRSpillRestore() {
1659 bool MadeChange = false;
1660 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1661 MachineInstr *MI = PushPopMIs[i];
1662 // First two operands are predicates.
1663 if (MI->getOpcode() == ARM::tPOP_RET &&
1664 MI->getOperand(2).getReg() == ARM::PC &&
1665 MI->getNumExplicitOperands() == 3) {
1666 // Create the new insn and copy the predicate from the old.
1667 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1668 .addOperand(MI->getOperand(0))
1669 .addOperand(MI->getOperand(1));
1670 MI->eraseFromParent();
1677 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1678 // below may shrink MI.
1680 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1681 switch(MI->getOpcode()) {
1682 // optimizeThumb2Instructions.
1683 case ARM::t2LEApcrel:
1685 // optimizeThumb2Branches.
1689 // optimizeThumb2JumpTables.
1696 bool ARMConstantIslands::optimizeThumb2Instructions() {
1697 bool MadeChange = false;
1699 // Shrink ADR and LDR from constantpool.
1700 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1701 CPUser &U = CPUsers[i];
1702 unsigned Opcode = U.MI->getOpcode();
1703 unsigned NewOpc = 0;
1708 case ARM::t2LEApcrel:
1709 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1710 NewOpc = ARM::tLEApcrel;
1716 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1717 NewOpc = ARM::tLDRpci;
1727 unsigned UserOffset = getUserOffset(U);
1728 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1730 // Be conservative with inline asm.
1731 if (!U.KnownAlignment)
1734 // FIXME: Check if offset is multiple of scale if scale is not 4.
1735 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1736 DEBUG(dbgs() << "Shrink: " << *U.MI);
1737 U.MI->setDesc(TII->get(NewOpc));
1738 MachineBasicBlock *MBB = U.MI->getParent();
1739 BBInfo[MBB->getNumber()].Size -= 2;
1740 adjustBBOffsetsAfter(MBB);
1746 MadeChange |= optimizeThumb2Branches();
1747 MadeChange |= optimizeThumb2JumpTables();
1751 bool ARMConstantIslands::optimizeThumb2Branches() {
1752 bool MadeChange = false;
1754 // The order in which branches appear in ImmBranches is approximately their
1755 // order within the function body. By visiting later branches first, we reduce
1756 // the distance between earlier forward branches and their targets, making it
1757 // more likely that the cbn?z optimization, which can only apply to forward
1758 // branches, will succeed.
1759 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1760 ImmBranch &Br = ImmBranches[i-1];
1761 unsigned Opcode = Br.MI->getOpcode();
1762 unsigned NewOpc = 0;
1780 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1781 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1782 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1783 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1784 Br.MI->setDesc(TII->get(NewOpc));
1785 MachineBasicBlock *MBB = Br.MI->getParent();
1786 BBInfo[MBB->getNumber()].Size -= 2;
1787 adjustBBOffsetsAfter(MBB);
1793 Opcode = Br.MI->getOpcode();
1794 if (Opcode != ARM::tBcc)
1797 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1798 // so this transformation is not safe.
1799 if (!Br.MI->killsRegister(ARM::CPSR))
1803 unsigned PredReg = 0;
1804 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
1805 if (Pred == ARMCC::EQ)
1807 else if (Pred == ARMCC::NE)
1808 NewOpc = ARM::tCBNZ;
1811 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1812 // Check if the distance is within 126. Subtract starting offset by 2
1813 // because the cmp will be eliminated.
1814 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1815 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1816 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1817 MachineBasicBlock::iterator CmpMI = Br.MI;
1818 if (CmpMI != Br.MI->getParent()->begin()) {
1820 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1821 unsigned Reg = CmpMI->getOperand(0).getReg();
1822 Pred = getInstrPredicate(CmpMI, PredReg);
1823 if (Pred == ARMCC::AL &&
1824 CmpMI->getOperand(1).getImm() == 0 &&
1825 isARMLowRegister(Reg)) {
1826 MachineBasicBlock *MBB = Br.MI->getParent();
1827 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1828 MachineInstr *NewBR =
1829 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1830 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1831 CmpMI->eraseFromParent();
1832 Br.MI->eraseFromParent();
1834 BBInfo[MBB->getNumber()].Size -= 2;
1835 adjustBBOffsetsAfter(MBB);
1847 /// If we've formed a TBB or TBH instruction, the base register is now
1848 /// redundant. In most cases, the instructions defining it will now be dead and
1849 /// can be tidied up. This function removes them if so, and returns the number
1851 unsigned ARMConstantIslands::removeDeadDefinitions(MachineInstr *MI,
1854 unsigned BytesRemoved = 0;
1855 MachineBasicBlock *MBB = MI->getParent();
1857 // Scan backwards to find the instruction that defines the base
1858 // register. Due to post-RA scheduling, we can't count on it
1859 // immediately preceding the branch instruction.
1860 MachineBasicBlock::iterator PrevI = MI;
1861 MachineBasicBlock::iterator B = MBB->begin();
1862 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1865 // If for some reason we didn't find it, we can't do anything, so
1866 // just skip this one.
1867 if (!PrevI->definesRegister(BaseReg) || PrevI->hasUnmodeledSideEffects() ||
1869 return BytesRemoved;
1871 MachineInstr *AddrMI = PrevI;
1872 unsigned NewBaseReg = BytesRemoved;
1874 // Examine the instruction that calculates the jumptable entry address. Make
1875 // sure it only defines the base register and kills any uses other than the
1876 // index register. We also need precisely one use to trace backwards to
1877 // (hopefully) the LEA.
1878 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1879 const MachineOperand &MO = AddrMI->getOperand(k);
1880 if (!MO.isReg() || !MO.getReg())
1882 if (MO.isDef() && MO.getReg() != BaseReg)
1883 return BytesRemoved;
1885 if (MO.isUse() && MO.getReg() != IdxReg) {
1886 if (!MO.isKill() || (NewBaseReg != 0 && NewBaseReg != MO.getReg()))
1887 return BytesRemoved;
1888 NewBaseReg = MO.getReg();
1892 // Want to continue searching for AddrMI, but there are 2 problems: AddrMI is
1893 // going away soon, and even decrementing once may be invalid.
1895 PrevI = std::prev(PrevI);
1897 DEBUG(dbgs() << "remove addr: " << *AddrMI);
1898 BytesRemoved += TII->GetInstSizeInBytes(AddrMI);
1899 AddrMI->eraseFromParent();
1901 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1902 // that gave us the initial base register definition.
1903 for (; PrevI != B && !PrevI->definesRegister(NewBaseReg); --PrevI)
1906 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1907 // to delete it as well.
1908 MachineInstr *LeaMI = PrevI;
1909 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1910 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1911 LeaMI->getOperand(0).getReg() != NewBaseReg)
1912 return BytesRemoved;
1914 DEBUG(dbgs() << "remove lea: " << *LeaMI);
1915 BytesRemoved += TII->GetInstSizeInBytes(LeaMI);
1916 LeaMI->eraseFromParent();
1917 return BytesRemoved;
1920 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1921 /// jumptables when it's possible.
1922 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1923 bool MadeChange = false;
1925 // FIXME: After the tables are shrunk, can we get rid some of the
1926 // constantpool tables?
1927 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1928 if (!MJTI) return false;
1930 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1931 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1932 MachineInstr *MI = T2JumpTables[i];
1933 const MCInstrDesc &MCID = MI->getDesc();
1934 unsigned NumOps = MCID.getNumOperands();
1935 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1936 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1937 unsigned JTI = JTOP.getIndex();
1938 assert(JTI < JT.size());
1941 bool HalfWordOk = true;
1942 unsigned JTOffset = getOffsetOf(MI) + 4;
1943 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1944 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1945 MachineBasicBlock *MBB = JTBBs[j];
1946 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1947 // Negative offset is not ok. FIXME: We should change BB layout to make
1948 // sure all the branches are forward.
1949 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1951 unsigned TBHLimit = ((1<<16)-1)*2;
1952 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1954 if (!ByteOk && !HalfWordOk)
1958 if (ByteOk || HalfWordOk) {
1959 MachineBasicBlock *MBB = MI->getParent();
1960 unsigned BaseReg = MI->getOperand(0).getReg();
1961 bool BaseRegKill = MI->getOperand(0).isKill();
1964 unsigned IdxReg = MI->getOperand(1).getReg();
1965 bool IdxRegKill = MI->getOperand(1).isKill();
1967 DEBUG(dbgs() << "Shrink JT: " << *MI);
1968 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1969 MachineBasicBlock::iterator MI_JT = MI;
1970 MachineInstr *NewJTMI =
1971 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
1972 .addReg(IdxReg, getKillRegState(IdxRegKill))
1973 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1974 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1975 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1976 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1977 // is 2-byte aligned. For now, asm printer will fix it up.
1978 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1979 unsigned OrigSize = TII->GetInstSizeInBytes(MI);
1980 unsigned DeadSize = removeDeadDefinitions(MI, BaseReg, IdxReg);
1981 MI->eraseFromParent();
1983 int delta = OrigSize - NewSize + DeadSize;
1984 BBInfo[MBB->getNumber()].Size -= delta;
1985 adjustBBOffsetsAfter(MBB);
1995 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1996 /// jump tables always branch forwards, since that's what tbb and tbh need.
1997 bool ARMConstantIslands::reorderThumb2JumpTables() {
1998 bool MadeChange = false;
2000 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2001 if (!MJTI) return false;
2003 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2004 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2005 MachineInstr *MI = T2JumpTables[i];
2006 const MCInstrDesc &MCID = MI->getDesc();
2007 unsigned NumOps = MCID.getNumOperands();
2008 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
2009 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2010 unsigned JTI = JTOP.getIndex();
2011 assert(JTI < JT.size());
2013 // We prefer if target blocks for the jump table come after the jump
2014 // instruction so we can use TB[BH]. Loop through the target blocks
2015 // and try to adjust them such that that's true.
2016 int JTNumber = MI->getParent()->getNumber();
2017 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2018 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2019 MachineBasicBlock *MBB = JTBBs[j];
2020 int DTNumber = MBB->getNumber();
2022 if (DTNumber < JTNumber) {
2023 // The destination precedes the switch. Try to move the block forward
2024 // so we have a positive offset.
2025 MachineBasicBlock *NewBB =
2026 adjustJTTargetBlockForward(MBB, MI->getParent());
2028 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2037 MachineBasicBlock *ARMConstantIslands::
2038 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2039 // If the destination block is terminated by an unconditional branch,
2040 // try to move it; otherwise, create a new block following the jump
2041 // table that branches back to the actual target. This is a very simple
2042 // heuristic. FIXME: We can definitely improve it.
2043 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2044 SmallVector<MachineOperand, 4> Cond;
2045 SmallVector<MachineOperand, 4> CondPrior;
2046 MachineFunction::iterator BBi = BB;
2047 MachineFunction::iterator OldPrior = std::prev(BBi);
2049 // If the block terminator isn't analyzable, don't try to move the block
2050 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2052 // If the block ends in an unconditional branch, move it. The prior block
2053 // has to have an analyzable terminator for us to move this one. Be paranoid
2054 // and make sure we're not trying to move the entry block of the function.
2055 if (!B && Cond.empty() && BB != MF->begin() &&
2056 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2057 BB->moveAfter(JTBB);
2058 OldPrior->updateTerminator();
2059 BB->updateTerminator();
2060 // Update numbering to account for the block being moved.
2061 MF->RenumberBlocks();
2066 // Create a new MBB for the code after the jump BB.
2067 MachineBasicBlock *NewBB =
2068 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2069 MachineFunction::iterator MBBI = JTBB; ++MBBI;
2070 MF->insert(MBBI, NewBB);
2072 // Add an unconditional branch from NewBB to BB.
2073 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2074 // correspond directly to anything in the source.
2075 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2076 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2077 .addImm(ARMCC::AL).addReg(0);
2079 // Update internal data structures to account for the newly inserted MBB.
2080 MF->RenumberBlocks(NewBB);
2083 NewBB->addSuccessor(BB);
2084 JTBB->removeSuccessor(BB);
2085 JTBB->addSuccessor(NewBB);