1 //===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
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 //===----------------------------------------------------------------------===//
11 // This pass is used to make Pc relative loads of constants.
12 // For now, only Mips16 will use this.
14 // Loading constants inline is expensive on Mips16 and it's in general better
15 // to place the constant nearby in code space and then it can be loaded with a
16 // simple 16 bit load instruction.
18 // The constants can be not just numbers but addresses of functions and labels.
19 // This can be particularly helpful in static relocation mode for embedded
25 #include "MCTargetDesc/MipsBaseInfo.h"
26 #include "Mips16InstrInfo.h"
27 #include "MipsMachineFunction.h"
28 #include "MipsTargetMachine.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
48 #define DEBUG_TYPE "mips-constant-islands"
50 STATISTIC(NumCPEs, "Number of constpool entries");
51 STATISTIC(NumSplit, "Number of uncond branches inserted");
52 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
53 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
55 // FIXME: This option should be removed once it has received sufficient testing.
57 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
58 cl::desc("Align constant islands in code"));
61 // Rather than do make check tests with huge amounts of code, we force
62 // the test to use this amount.
64 static cl::opt<int> ConstantIslandsSmallOffset(
65 "mips-constant-islands-small-offset",
67 cl::desc("Make small offsets be this amount for testing purposes"),
71 // For testing purposes we tell it to not use relaxed load forms so that it
74 static cl::opt<bool> NoLoadRelaxation(
75 "mips-constant-islands-no-load-relaxation",
77 cl::desc("Don't relax loads to long loads - for testing purposes"),
80 static unsigned int branchTargetOperand(MachineInstr *MI) {
81 switch (MI->getOpcode()) {
90 case Mips::BeqzRxImm16:
91 case Mips::BeqzRxImmX16:
92 case Mips::BnezRxImm16:
93 case Mips::BnezRxImmX16:
96 llvm_unreachable("Unknown branch type");
99 static bool isUnconditionalBranch(unsigned int Opcode) {
101 default: return false;
109 static unsigned int longformBranchOpcode(unsigned int Opcode) {
113 return Mips::BimmX16;
116 return Mips::BteqzX16;
119 return Mips::BtnezX16;
122 case Mips::BeqzRxImm16:
123 case Mips::BeqzRxImmX16:
124 return Mips::BeqzRxImmX16;
125 case Mips::BnezRxImm16:
126 case Mips::BnezRxImmX16:
127 return Mips::BnezRxImmX16;
129 llvm_unreachable("Unknown branch type");
133 // FIXME: need to go through this whole constant islands port and check the math
134 // for branch ranges and clean this up and make some functions to calculate things
135 // that are done many times identically.
136 // Need to refactor some of the code to call this routine.
138 static unsigned int branchMaxOffsets(unsigned int Opcode) {
139 unsigned Bits, Scale;
149 case Mips::BeqzRxImm16:
153 case Mips::BeqzRxImmX16:
157 case Mips::BnezRxImm16:
161 case Mips::BnezRxImmX16:
182 llvm_unreachable("Unknown branch type");
184 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
191 typedef MachineBasicBlock::iterator Iter;
192 typedef MachineBasicBlock::reverse_iterator ReverseIter;
194 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
195 /// requires constant pool entries to be scattered among the instructions
196 /// inside a function. To do this, it completely ignores the normal LLVM
197 /// constant pool; instead, it places constants wherever it feels like with
198 /// special instructions.
200 /// The terminology used in this pass includes:
201 /// Islands - Clumps of constants placed in the function.
202 /// Water - Potential places where an island could be formed.
203 /// CPE - A constant pool entry that has been placed somewhere, which
204 /// tracks a list of users.
206 class MipsConstantIslands : public MachineFunctionPass {
208 /// BasicBlockInfo - Information about the offset and size of a single
210 struct BasicBlockInfo {
211 /// Offset - Distance from the beginning of the function to the beginning
212 /// of this basic block.
214 /// Offsets are computed assuming worst case padding before an aligned
215 /// block. This means that subtracting basic block offsets always gives a
216 /// conservative estimate of the real distance which may be smaller.
218 /// Because worst case padding is used, the computed offset of an aligned
219 /// block may not actually be aligned.
222 /// Size - Size of the basic block in bytes. If the block contains
223 /// inline assembly, this is a worst case estimate.
225 /// The size does not include any alignment padding whether from the
226 /// beginning of the block, or from an aligned jump table at the end.
229 // FIXME: ignore LogAlign for this patch
231 unsigned postOffset(unsigned LogAlign = 0) const {
232 unsigned PO = Offset + Size;
236 BasicBlockInfo() : Offset(0), Size(0) {}
240 std::vector<BasicBlockInfo> BBInfo;
242 /// WaterList - A sorted list of basic blocks where islands could be placed
243 /// (i.e. blocks that don't fall through to the following block, due
244 /// to a return, unreachable, or unconditional branch).
245 std::vector<MachineBasicBlock*> WaterList;
247 /// NewWaterList - The subset of WaterList that was created since the
248 /// previous iteration by inserting unconditional branches.
249 SmallSet<MachineBasicBlock*, 4> NewWaterList;
251 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
253 /// CPUser - One user of a constant pool, keeping the machine instruction
254 /// pointer, the constant pool being referenced, and the max displacement
255 /// allowed from the instruction to the CP. The HighWaterMark records the
256 /// highest basic block where a new CPEntry can be placed. To ensure this
257 /// pass terminates, the CP entries are initially placed at the end of the
258 /// function and then move monotonically to lower addresses. The
259 /// exception to this rule is when the current CP entry for a particular
260 /// CPUser is out of range, but there is another CP entry for the same
261 /// constant value in range. We want to use the existing in-range CP
262 /// entry, but if it later moves out of range, the search for new water
263 /// should resume where it left off. The HighWaterMark is used to record
268 MachineBasicBlock *HighWaterMark;
271 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
272 // with different displacements
273 unsigned LongFormOpcode;
276 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
278 unsigned longformmaxdisp, unsigned longformopcode)
279 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
280 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
282 HighWaterMark = CPEMI->getParent();
284 /// getMaxDisp - Returns the maximum displacement supported by MI.
285 unsigned getMaxDisp() const {
286 unsigned xMaxDisp = ConstantIslandsSmallOffset?
287 ConstantIslandsSmallOffset: MaxDisp;
290 void setMaxDisp(unsigned val) {
293 unsigned getLongFormMaxDisp() const {
294 return LongFormMaxDisp;
296 unsigned getLongFormOpcode() const {
297 return LongFormOpcode;
301 /// CPUsers - Keep track of all of the machine instructions that use various
302 /// constant pools and their max displacement.
303 std::vector<CPUser> CPUsers;
305 /// CPEntry - One per constant pool entry, keeping the machine instruction
306 /// pointer, the constpool index, and the number of CPUser's which
307 /// reference this entry.
312 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
313 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
316 /// CPEntries - Keep track of all of the constant pool entry machine
317 /// instructions. For each original constpool index (i.e. those that
318 /// existed upon entry to this pass), it keeps a vector of entries.
319 /// Original elements are cloned as we go along; the clones are
320 /// put in the vector of the original element, but have distinct CPIs.
321 std::vector<std::vector<CPEntry> > CPEntries;
323 /// ImmBranch - One per immediate branch, keeping the machine instruction
324 /// pointer, conditional or unconditional, the max displacement,
325 /// and (if isCond is true) the corresponding unconditional branch
329 unsigned MaxDisp : 31;
332 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
333 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
336 /// ImmBranches - Keep track of all the immediate branch instructions.
338 std::vector<ImmBranch> ImmBranches;
340 /// HasFarJump - True if any far jump instruction has been emitted during
341 /// the branch fix up pass.
344 const TargetMachine &TM;
347 const MipsSubtarget *STI;
348 const Mips16InstrInfo *TII;
349 MipsFunctionInfo *MFI;
351 MachineConstantPool *MCP;
353 unsigned PICLabelUId;
354 bool PrescannedForConstants;
356 void initPICLabelUId(unsigned UId) {
361 unsigned createPICLabelUId() {
362 return PICLabelUId++;
367 MipsConstantIslands(TargetMachine &tm)
368 : MachineFunctionPass(ID), TM(tm),
369 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
370 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()), STI(nullptr),
371 MF(nullptr), MCP(nullptr), PrescannedForConstants(false) {}
373 const char *getPassName() const override {
374 return "Mips Constant Islands";
377 bool runOnMachineFunction(MachineFunction &F) override;
379 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
380 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
381 unsigned getCPELogAlign(const MachineInstr *CPEMI);
382 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
383 unsigned getOffsetOf(MachineInstr *MI) const;
384 unsigned getUserOffset(CPUser&) const;
387 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
388 unsigned Disp, bool NegativeOK);
389 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
392 void computeBlockSize(MachineBasicBlock *MBB);
393 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
394 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
395 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
396 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
397 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
398 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
399 bool findAvailableWater(CPUser&U, unsigned UserOffset,
400 water_iterator &WaterIter);
401 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
402 MachineBasicBlock *&NewMBB);
403 bool handleConstantPoolUser(unsigned CPUserIndex);
404 void removeDeadCPEMI(MachineInstr *CPEMI);
405 bool removeUnusedCPEntries();
406 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
407 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
408 bool DoDump = false);
409 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
410 CPUser &U, unsigned &Growth);
411 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
412 bool fixupImmediateBr(ImmBranch &Br);
413 bool fixupConditionalBr(ImmBranch &Br);
414 bool fixupUnconditionalBr(ImmBranch &Br);
416 void prescanForConstants();
422 char MipsConstantIslands::ID = 0;
423 } // end of anonymous namespace
425 bool MipsConstantIslands::isOffsetInRange
426 (unsigned UserOffset, unsigned TrialOffset,
428 return isOffsetInRange(UserOffset, TrialOffset,
429 U.getMaxDisp(), U.NegOk);
431 /// print block size and offset information - debugging
432 void MipsConstantIslands::dumpBBs() {
434 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
435 const BasicBlockInfo &BBI = BBInfo[J];
436 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
437 << format(" size=%#x\n", BBInfo[J].Size);
441 /// createMipsLongBranchPass - Returns a pass that converts branches to long
443 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
444 return new MipsConstantIslands(tm);
447 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
448 // The intention is for this to be a mips16 only pass for now
451 MCP = mf.getConstantPool();
452 STI = &mf.getTarget().getSubtarget<MipsSubtarget>();
453 DEBUG(dbgs() << "constant island machine function " << "\n");
454 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
457 TII = (const Mips16InstrInfo *)MF->getTarget()
460 MFI = MF->getInfo<MipsFunctionInfo>();
461 DEBUG(dbgs() << "constant island processing " << "\n");
463 // will need to make predermination if there is any constants we need to
464 // put in constant islands. TBD.
466 if (!PrescannedForConstants) prescanForConstants();
469 // This pass invalidates liveness information when it splits basic blocks.
470 MF->getRegInfo().invalidateLiveness();
472 // Renumber all of the machine basic blocks in the function, guaranteeing that
473 // the numbers agree with the position of the block in the function.
474 MF->RenumberBlocks();
476 bool MadeChange = false;
478 // Perform the initial placement of the constant pool entries. To start with,
479 // we put them all at the end of the function.
480 std::vector<MachineInstr*> CPEMIs;
482 doInitialPlacement(CPEMIs);
484 /// The next UID to take is the first unused one.
485 initPICLabelUId(CPEMIs.size());
487 // Do the initial scan of the function, building up information about the
488 // sizes of each block, the location of all the water, and finding all of the
489 // constant pool users.
490 initializeFunctionInfo(CPEMIs);
494 /// Remove dead constant pool entries.
495 MadeChange |= removeUnusedCPEntries();
497 // Iteratively place constant pool entries and fix up branches until there
499 unsigned NoCPIters = 0, NoBRIters = 0;
502 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
503 bool CPChange = false;
504 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
505 CPChange |= handleConstantPoolUser(i);
506 if (CPChange && ++NoCPIters > 30)
507 report_fatal_error("Constant Island pass failed to converge!");
510 // Clear NewWaterList now. If we split a block for branches, it should
511 // appear as "new water" for the next iteration of constant pool placement.
512 NewWaterList.clear();
514 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
515 bool BRChange = false;
516 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
517 BRChange |= fixupImmediateBr(ImmBranches[i]);
518 if (BRChange && ++NoBRIters > 30)
519 report_fatal_error("Branch Fix Up pass failed to converge!");
521 if (!CPChange && !BRChange)
526 DEBUG(dbgs() << '\n'; dumpBBs());
536 /// doInitialPlacement - Perform the initial placement of the constant pool
537 /// entries. To start with, we put them all at the end of the function.
539 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
540 // Create the basic block to hold the CPE's.
541 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
545 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
546 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
548 // Mark the basic block as required by the const-pool.
549 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
550 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
552 // The function needs to be as aligned as the basic blocks. The linker may
553 // move functions around based on their alignment.
554 MF->ensureAlignment(BB->getAlignment());
556 // Order the entries in BB by descending alignment. That ensures correct
557 // alignment of all entries as long as BB is sufficiently aligned. Keep
558 // track of the insertion point for each alignment. We are going to bucket
559 // sort the entries as they are created.
560 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
562 // Add all of the constants from the constant pool to the end block, use an
563 // identity mapping of CPI's to CPE's.
564 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
566 const DataLayout &TD = *MF->getSubtarget().getDataLayout();
567 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
568 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
569 assert(Size >= 4 && "Too small constant pool entry");
570 unsigned Align = CPs[i].getAlignment();
571 assert(isPowerOf2_32(Align) && "Invalid alignment");
572 // Verify that all constant pool entries are a multiple of their alignment.
573 // If not, we would have to pad them out so that instructions stay aligned.
574 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
576 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
577 unsigned LogAlign = Log2_32(Align);
578 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
580 MachineInstr *CPEMI =
581 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
582 .addImm(i).addConstantPoolIndex(i).addImm(Size);
584 CPEMIs.push_back(CPEMI);
586 // Ensure that future entries with higher alignment get inserted before
587 // CPEMI. This is bucket sort with iterators.
588 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
589 if (InsPoint[a] == InsAt)
591 // Add a new CPEntry, but no corresponding CPUser yet.
592 std::vector<CPEntry> CPEs;
593 CPEs.push_back(CPEntry(CPEMI, i));
594 CPEntries.push_back(CPEs);
596 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
597 << Size << ", align = " << Align <<'\n');
602 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
603 /// into the block immediately after it.
604 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
605 // Get the next machine basic block in the function.
606 MachineFunction::iterator MBBI = MBB;
607 // Can't fall off end of function.
608 if (std::next(MBBI) == MBB->getParent()->end())
611 MachineBasicBlock *NextBB = std::next(MBBI);
612 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
613 E = MBB->succ_end(); I != E; ++I)
620 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
621 /// look up the corresponding CPEntry.
622 MipsConstantIslands::CPEntry
623 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
624 const MachineInstr *CPEMI) {
625 std::vector<CPEntry> &CPEs = CPEntries[CPI];
626 // Number of entries per constpool index should be small, just do a
628 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
629 if (CPEs[i].CPEMI == CPEMI)
635 /// getCPELogAlign - Returns the required alignment of the constant pool entry
636 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
637 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
638 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
640 // Everything is 4-byte aligned unless AlignConstantIslands is set.
641 if (!AlignConstantIslands)
644 unsigned CPI = CPEMI->getOperand(1).getIndex();
645 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
646 unsigned Align = MCP->getConstants()[CPI].getAlignment();
647 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
648 return Log2_32(Align);
651 /// initializeFunctionInfo - Do the initial scan of the function, building up
652 /// information about the sizes of each block, the location of all the water,
653 /// and finding all of the constant pool users.
654 void MipsConstantIslands::
655 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
657 BBInfo.resize(MF->getNumBlockIDs());
659 // First thing, compute the size of all basic blocks, and see if the function
660 // has any inline assembly in it. If so, we have to be conservative about
661 // alignment assumptions, as we don't know for sure the size of any
662 // instructions in the inline assembly.
663 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
667 // Compute block offsets.
668 adjustBBOffsetsAfter(MF->begin());
670 // Now go back through the instructions and build up our data structures.
671 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
673 MachineBasicBlock &MBB = *MBBI;
675 // If this block doesn't fall through into the next MBB, then this is
676 // 'water' that a constant pool island could be placed.
677 if (!BBHasFallthrough(&MBB))
678 WaterList.push_back(&MBB);
679 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
681 if (I->isDebugValue())
684 int Opc = I->getOpcode();
692 continue; // Ignore other branches for now
703 case Mips::BeqzRxImm16:
709 case Mips::BeqzRxImmX16:
715 case Mips::BnezRxImm16:
721 case Mips::BnezRxImmX16:
752 // Record this immediate branch.
753 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
754 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
757 if (Opc == Mips::CONSTPOOL_ENTRY)
761 // Scan the instructions for constant pool operands.
762 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
763 if (I->getOperand(op).isCPI()) {
765 // We found one. The addressing mode tells us the max displacement
766 // from the PC that this instruction permits.
768 // Basic size info comes from the TSFlags field.
772 unsigned LongFormBits = 0;
773 unsigned LongFormScale = 0;
774 unsigned LongFormOpcode = 0;
777 llvm_unreachable("Unknown addressing mode for CP reference!");
778 case Mips::LwRxPcTcp16:
781 LongFormOpcode = Mips::LwRxPcTcpX16;
785 case Mips::LwRxPcTcpX16:
791 // Remember that this is a user of a CP entry.
792 unsigned CPI = I->getOperand(op).getIndex();
793 MachineInstr *CPEMI = CPEMIs[CPI];
794 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
795 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
796 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
797 LongFormMaxOffs, LongFormOpcode));
799 // Increment corresponding CPEntry reference count.
800 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
801 assert(CPE && "Cannot find a corresponding CPEntry!");
804 // Instructions can only use one CP entry, don't bother scanning the
805 // rest of the operands.
815 /// computeBlockSize - Compute the size and some alignment information for MBB.
816 /// This function updates BBInfo directly.
817 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
818 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
821 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
823 BBI.Size += TII->GetInstSizeInBytes(I);
827 /// getOffsetOf - Return the current offset of the specified machine instruction
828 /// from the start of the function. This offset changes as stuff is moved
829 /// around inside the function.
830 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
831 MachineBasicBlock *MBB = MI->getParent();
833 // The offset is composed of two things: the sum of the sizes of all MBB's
834 // before this instruction's block, and the offset from the start of the block
836 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
838 // Sum instructions before MI in MBB.
839 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
840 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
841 Offset += TII->GetInstSizeInBytes(I);
846 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
848 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
849 const MachineBasicBlock *RHS) {
850 return LHS->getNumber() < RHS->getNumber();
853 /// updateForInsertedWaterBlock - When a block is newly inserted into the
854 /// machine function, it upsets all of the block numbers. Renumber the blocks
855 /// and update the arrays that parallel this numbering.
856 void MipsConstantIslands::updateForInsertedWaterBlock
857 (MachineBasicBlock *NewBB) {
858 // Renumber the MBB's to keep them consecutive.
859 NewBB->getParent()->RenumberBlocks(NewBB);
861 // Insert an entry into BBInfo to align it properly with the (newly
862 // renumbered) block numbers.
863 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
865 // Next, update WaterList. Specifically, we need to add NewMBB as having
866 // available water after it.
868 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
870 WaterList.insert(IP, NewBB);
873 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
874 return getOffsetOf(U.MI);
877 /// Split the basic block containing MI into two blocks, which are joined by
878 /// an unconditional branch. Update data structures and renumber blocks to
879 /// account for this change and returns the newly created block.
880 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
882 MachineBasicBlock *OrigBB = MI->getParent();
884 // Create a new MBB for the code after the OrigBB.
885 MachineBasicBlock *NewBB =
886 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
887 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
888 MF->insert(MBBI, NewBB);
890 // Splice the instructions starting with MI over to NewBB.
891 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
893 // Add an unconditional branch from OrigBB to NewBB.
894 // Note the new unconditional branch is not being recorded.
895 // There doesn't seem to be meaningful DebugInfo available; this doesn't
896 // correspond to anything in the source.
897 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
900 // Update the CFG. All succs of OrigBB are now succs of NewBB.
901 NewBB->transferSuccessors(OrigBB);
903 // OrigBB branches to NewBB.
904 OrigBB->addSuccessor(NewBB);
906 // Update internal data structures to account for the newly inserted MBB.
907 // This is almost the same as updateForInsertedWaterBlock, except that
908 // the Water goes after OrigBB, not NewBB.
909 MF->RenumberBlocks(NewBB);
911 // Insert an entry into BBInfo to align it properly with the (newly
912 // renumbered) block numbers.
913 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
915 // Next, update WaterList. Specifically, we need to add OrigMBB as having
916 // available water after it (but not if it's already there, which happens
917 // when splitting before a conditional branch that is followed by an
918 // unconditional branch - in that case we want to insert NewBB).
920 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
922 MachineBasicBlock* WaterBB = *IP;
923 if (WaterBB == OrigBB)
924 WaterList.insert(std::next(IP), NewBB);
926 WaterList.insert(IP, OrigBB);
927 NewWaterList.insert(OrigBB);
929 // Figure out how large the OrigBB is. As the first half of the original
930 // block, it cannot contain a tablejump. The size includes
931 // the new jump we added. (It should be possible to do this without
932 // recounting everything, but it's very confusing, and this is rarely
934 computeBlockSize(OrigBB);
936 // Figure out how large the NewMBB is. As the second half of the original
937 // block, it may contain a tablejump.
938 computeBlockSize(NewBB);
940 // All BBOffsets following these blocks must be modified.
941 adjustBBOffsetsAfter(OrigBB);
948 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
949 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
950 /// constant pool entry).
951 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
952 unsigned TrialOffset, unsigned MaxDisp,
954 if (UserOffset <= TrialOffset) {
955 // User before the Trial.
956 if (TrialOffset - UserOffset <= MaxDisp)
958 } else if (NegativeOK) {
959 if (UserOffset - TrialOffset <= MaxDisp)
965 /// isWaterInRange - Returns true if a CPE placed after the specified
966 /// Water (a basic block) will be in range for the specific MI.
968 /// Compute how much the function will grow by inserting a CPE after Water.
969 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
970 MachineBasicBlock* Water, CPUser &U,
972 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
973 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
974 unsigned NextBlockOffset, NextBlockAlignment;
975 MachineFunction::const_iterator NextBlock = Water;
976 if (++NextBlock == MF->end()) {
977 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
978 NextBlockAlignment = 0;
980 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
981 NextBlockAlignment = NextBlock->getAlignment();
983 unsigned Size = U.CPEMI->getOperand(2).getImm();
984 unsigned CPEEnd = CPEOffset + Size;
986 // The CPE may be able to hide in the alignment padding before the next
987 // block. It may also cause more padding to be required if it is more aligned
988 // that the next block.
989 if (CPEEnd > NextBlockOffset) {
990 Growth = CPEEnd - NextBlockOffset;
991 // Compute the padding that would go at the end of the CPE to align the next
993 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
995 // If the CPE is to be inserted before the instruction, that will raise
996 // the offset of the instruction. Also account for unknown alignment padding
997 // in blocks between CPE and the user.
998 if (CPEOffset < UserOffset)
999 UserOffset += Growth;
1001 // CPE fits in existing padding.
1004 return isOffsetInRange(UserOffset, CPEOffset, U);
1007 /// isCPEntryInRange - Returns true if the distance between specific MI and
1008 /// specific ConstPool entry instruction can fit in MI's displacement field.
1009 bool MipsConstantIslands::isCPEntryInRange
1010 (MachineInstr *MI, unsigned UserOffset,
1011 MachineInstr *CPEMI, unsigned MaxDisp,
1012 bool NegOk, bool DoDump) {
1013 unsigned CPEOffset = getOffsetOf(CPEMI);
1017 unsigned Block = MI->getParent()->getNumber();
1018 const BasicBlockInfo &BBI = BBInfo[Block];
1019 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1020 << " max delta=" << MaxDisp
1021 << format(" insn address=%#x", UserOffset)
1022 << " in BB#" << Block << ": "
1023 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1024 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1025 int(CPEOffset-UserOffset));
1029 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1033 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1034 /// unconditionally branches to its only successor.
1035 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1036 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1038 MachineBasicBlock *Succ = *MBB->succ_begin();
1039 MachineBasicBlock *Pred = *MBB->pred_begin();
1040 MachineInstr *PredMI = &Pred->back();
1041 if (PredMI->getOpcode() == Mips::Bimm16)
1042 return PredMI->getOperand(0).getMBB() == Succ;
1047 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1048 unsigned BBNum = BB->getNumber();
1049 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1050 // Get the offset and known bits at the end of the layout predecessor.
1051 // Include the alignment of the current block.
1052 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1053 BBInfo[i].Offset = Offset;
1057 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1058 /// and instruction CPEMI, and decrement its refcount. If the refcount
1059 /// becomes 0 remove the entry and instruction. Returns true if we removed
1060 /// the entry, false if we didn't.
1062 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1063 MachineInstr *CPEMI) {
1064 // Find the old entry. Eliminate it if it is no longer used.
1065 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1066 assert(CPE && "Unexpected!");
1067 if (--CPE->RefCount == 0) {
1068 removeDeadCPEMI(CPEMI);
1069 CPE->CPEMI = nullptr;
1076 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1077 /// if not, see if an in-range clone of the CPE is in range, and if so,
1078 /// change the data structures so the user references the clone. Returns:
1079 /// 0 = no existing entry found
1080 /// 1 = entry found, and there were no code insertions or deletions
1081 /// 2 = entry found, and there were code insertions or deletions
1082 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1084 MachineInstr *UserMI = U.MI;
1085 MachineInstr *CPEMI = U.CPEMI;
1087 // Check to see if the CPE is already in-range.
1088 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1090 DEBUG(dbgs() << "In range\n");
1094 // No. Look for previously created clones of the CPE that are in range.
1095 unsigned CPI = CPEMI->getOperand(1).getIndex();
1096 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1097 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1098 // We already tried this one
1099 if (CPEs[i].CPEMI == CPEMI)
1101 // Removing CPEs can leave empty entries, skip
1102 if (CPEs[i].CPEMI == nullptr)
1104 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1106 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1107 << CPEs[i].CPI << "\n");
1108 // Point the CPUser node to the replacement
1109 U.CPEMI = CPEs[i].CPEMI;
1110 // Change the CPI in the instruction operand to refer to the clone.
1111 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1112 if (UserMI->getOperand(j).isCPI()) {
1113 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1116 // Adjust the refcount of the clone...
1118 // ...and the original. If we didn't remove the old entry, none of the
1119 // addresses changed, so we don't need another pass.
1120 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1126 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1127 /// This version checks if the longer form of the instruction can be used to
1128 /// to satisfy things.
1129 /// if not, see if an in-range clone of the CPE is in range, and if so,
1130 /// change the data structures so the user references the clone. Returns:
1131 /// 0 = no existing entry found
1132 /// 1 = entry found, and there were no code insertions or deletions
1133 /// 2 = entry found, and there were code insertions or deletions
1134 int MipsConstantIslands::findLongFormInRangeCPEntry
1135 (CPUser& U, unsigned UserOffset)
1137 MachineInstr *UserMI = U.MI;
1138 MachineInstr *CPEMI = U.CPEMI;
1140 // Check to see if the CPE is already in-range.
1141 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1142 U.getLongFormMaxDisp(), U.NegOk,
1144 DEBUG(dbgs() << "In range\n");
1145 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1146 U.setMaxDisp(U.getLongFormMaxDisp());
1147 return 2; // instruction is longer length now
1150 // No. Look for previously created clones of the CPE that are in range.
1151 unsigned CPI = CPEMI->getOperand(1).getIndex();
1152 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1153 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1154 // We already tried this one
1155 if (CPEs[i].CPEMI == CPEMI)
1157 // Removing CPEs can leave empty entries, skip
1158 if (CPEs[i].CPEMI == nullptr)
1160 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1161 U.getLongFormMaxDisp(), U.NegOk)) {
1162 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1163 << CPEs[i].CPI << "\n");
1164 // Point the CPUser node to the replacement
1165 U.CPEMI = CPEs[i].CPEMI;
1166 // Change the CPI in the instruction operand to refer to the clone.
1167 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1168 if (UserMI->getOperand(j).isCPI()) {
1169 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1172 // Adjust the refcount of the clone...
1174 // ...and the original. If we didn't remove the old entry, none of the
1175 // addresses changed, so we don't need another pass.
1176 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1182 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1183 /// the specific unconditional branch instruction.
1184 static inline unsigned getUnconditionalBrDisp(int Opc) {
1187 return ((1<<10)-1)*2;
1189 return ((1<<16)-1)*2;
1193 return ((1<<16)-1)*2;
1196 /// findAvailableWater - Look for an existing entry in the WaterList in which
1197 /// we can place the CPE referenced from U so it's within range of U's MI.
1198 /// Returns true if found, false if not. If it returns true, WaterIter
1199 /// is set to the WaterList entry.
1200 /// To ensure that this pass
1201 /// terminates, the CPE location for a particular CPUser is only allowed to
1202 /// move to a lower address, so search backward from the end of the list and
1203 /// prefer the first water that is in range.
1204 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1205 water_iterator &WaterIter) {
1206 if (WaterList.empty())
1209 unsigned BestGrowth = ~0u;
1210 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1212 MachineBasicBlock* WaterBB = *IP;
1213 // Check if water is in range and is either at a lower address than the
1214 // current "high water mark" or a new water block that was created since
1215 // the previous iteration by inserting an unconditional branch. In the
1216 // latter case, we want to allow resetting the high water mark back to
1217 // this new water since we haven't seen it before. Inserting branches
1218 // should be relatively uncommon and when it does happen, we want to be
1219 // sure to take advantage of it for all the CPEs near that block, so that
1220 // we don't insert more branches than necessary.
1222 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1223 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1224 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1225 // This is the least amount of required padding seen so far.
1226 BestGrowth = Growth;
1228 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1229 << " Growth=" << Growth << '\n');
1231 // Keep looking unless it is perfect.
1232 if (BestGrowth == 0)
1238 return BestGrowth != ~0u;
1241 /// createNewWater - No existing WaterList entry will work for
1242 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1243 /// block is used if in range, and the conditional branch munged so control
1244 /// flow is correct. Otherwise the block is split to create a hole with an
1245 /// unconditional branch around it. In either case NewMBB is set to a
1246 /// block following which the new island can be inserted (the WaterList
1247 /// is not adjusted).
1248 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1249 unsigned UserOffset,
1250 MachineBasicBlock *&NewMBB) {
1251 CPUser &U = CPUsers[CPUserIndex];
1252 MachineInstr *UserMI = U.MI;
1253 MachineInstr *CPEMI = U.CPEMI;
1254 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1255 MachineBasicBlock *UserMBB = UserMI->getParent();
1256 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1258 // If the block does not end in an unconditional branch already, and if the
1259 // end of the block is within range, make new water there.
1260 if (BBHasFallthrough(UserMBB)) {
1261 // Size of branch to insert.
1263 // Compute the offset where the CPE will begin.
1264 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1266 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1267 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1268 << format(", expected CPE offset %#x\n", CPEOffset));
1269 NewMBB = std::next(MachineFunction::iterator(UserMBB));
1270 // Add an unconditional branch from UserMBB to fallthrough block. Record
1271 // it for branch lengthening; this new branch will not get out of range,
1272 // but if the preceding conditional branch is out of range, the targets
1273 // will be exchanged, and the altered branch may be out of range, so the
1274 // machinery has to know about it.
1275 int UncondBr = Mips::Bimm16;
1276 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1277 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1278 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1279 MaxDisp, false, UncondBr));
1280 BBInfo[UserMBB->getNumber()].Size += Delta;
1281 adjustBBOffsetsAfter(UserMBB);
1286 // What a big block. Find a place within the block to split it.
1288 // Try to split the block so it's fully aligned. Compute the latest split
1289 // point where we can add a 4-byte branch instruction, and then align to
1290 // LogAlign which is the largest possible alignment in the function.
1291 unsigned LogAlign = MF->getAlignment();
1292 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1293 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
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 // Alignment of the island is handled
1299 // inside isOffsetInRange.
1300 BaseInsertOffset -= 4;
1302 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1303 << " la=" << LogAlign << '\n');
1305 // This could point off the end of the block if we've already got constant
1306 // pool entries following this block; only the last one is in the water list.
1307 // Back past any possible branches (allow for a conditional and a maximally
1308 // long unconditional).
1309 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1310 BaseInsertOffset = UserBBI.postOffset() - 8;
1311 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1313 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1314 CPEMI->getOperand(2).getImm();
1315 MachineBasicBlock::iterator MI = UserMI;
1317 unsigned CPUIndex = CPUserIndex+1;
1318 unsigned NumCPUsers = CPUsers.size();
1319 //MachineInstr *LastIT = 0;
1320 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1321 Offset < BaseInsertOffset;
1322 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1323 assert(MI != UserMBB->end() && "Fell off end of block");
1324 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1325 CPUser &U = CPUsers[CPUIndex];
1326 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1327 // Shift intertion point by one unit of alignment so it is within reach.
1328 BaseInsertOffset -= 1u << LogAlign;
1329 EndInsertOffset -= 1u << LogAlign;
1331 // This is overly conservative, as we don't account for CPEMIs being
1332 // reused within the block, but it doesn't matter much. Also assume CPEs
1333 // are added in order with alignment padding. We may eventually be able
1334 // to pack the aligned CPEs better.
1335 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1341 NewMBB = splitBlockBeforeInstr(MI);
1344 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1345 /// is out-of-range. If so, pick up the constant pool value and move it some
1346 /// place in-range. Return true if we changed any addresses (thus must run
1347 /// another pass of branch lengthening), false otherwise.
1348 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1349 CPUser &U = CPUsers[CPUserIndex];
1350 MachineInstr *UserMI = U.MI;
1351 MachineInstr *CPEMI = U.CPEMI;
1352 unsigned CPI = CPEMI->getOperand(1).getIndex();
1353 unsigned Size = CPEMI->getOperand(2).getImm();
1354 // Compute this only once, it's expensive.
1355 unsigned UserOffset = getUserOffset(U);
1357 // See if the current entry is within range, or there is a clone of it
1359 int result = findInRangeCPEntry(U, UserOffset);
1360 if (result==1) return false;
1361 else if (result==2) return true;
1364 // Look for water where we can place this CPE.
1365 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1366 MachineBasicBlock *NewMBB;
1368 if (findAvailableWater(U, UserOffset, IP)) {
1369 DEBUG(dbgs() << "Found water in range\n");
1370 MachineBasicBlock *WaterBB = *IP;
1372 // If the original WaterList entry was "new water" on this iteration,
1373 // propagate that to the new island. This is just keeping NewWaterList
1374 // updated to match the WaterList, which will be updated below.
1375 if (NewWaterList.erase(WaterBB))
1376 NewWaterList.insert(NewIsland);
1378 // The new CPE goes before the following block (NewMBB).
1379 NewMBB = std::next(MachineFunction::iterator(WaterBB));
1383 // we first see if a longer form of the instrucion could have reached
1384 // the constant. in that case we won't bother to split
1385 if (!NoLoadRelaxation) {
1386 result = findLongFormInRangeCPEntry(U, UserOffset);
1387 if (result != 0) return true;
1389 DEBUG(dbgs() << "No water found\n");
1390 createNewWater(CPUserIndex, UserOffset, NewMBB);
1392 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1393 // called while handling branches so that the water will be seen on the
1394 // next iteration for constant pools, but in this context, we don't want
1395 // it. Check for this so it will be removed from the WaterList.
1396 // Also remove any entry from NewWaterList.
1397 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1398 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1399 if (IP != WaterList.end())
1400 NewWaterList.erase(WaterBB);
1402 // We are adding new water. Update NewWaterList.
1403 NewWaterList.insert(NewIsland);
1406 // Remove the original WaterList entry; we want subsequent insertions in
1407 // this vicinity to go after the one we're about to insert. This
1408 // considerably reduces the number of times we have to move the same CPE
1409 // more than once and is also important to ensure the algorithm terminates.
1410 if (IP != WaterList.end())
1411 WaterList.erase(IP);
1413 // Okay, we know we can put an island before NewMBB now, do it!
1414 MF->insert(NewMBB, NewIsland);
1416 // Update internal data structures to account for the newly inserted MBB.
1417 updateForInsertedWaterBlock(NewIsland);
1419 // Decrement the old entry, and remove it if refcount becomes 0.
1420 decrementCPEReferenceCount(CPI, CPEMI);
1422 // No existing clone of this CPE is within range.
1423 // We will be generating a new clone. Get a UID for it.
1424 unsigned ID = createPICLabelUId();
1426 // Now that we have an island to add the CPE to, clone the original CPE and
1427 // add it to the island.
1428 U.HighWaterMark = NewIsland;
1429 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1430 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1431 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1434 // Mark the basic block as aligned as required by the const-pool entry.
1435 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1437 // Increase the size of the island block to account for the new entry.
1438 BBInfo[NewIsland->getNumber()].Size += Size;
1439 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1443 // Finally, change the CPI in the instruction operand to be ID.
1444 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1445 if (UserMI->getOperand(i).isCPI()) {
1446 UserMI->getOperand(i).setIndex(ID);
1450 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1451 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1456 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1457 /// sizes and offsets of impacted basic blocks.
1458 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1459 MachineBasicBlock *CPEBB = CPEMI->getParent();
1460 unsigned Size = CPEMI->getOperand(2).getImm();
1461 CPEMI->eraseFromParent();
1462 BBInfo[CPEBB->getNumber()].Size -= Size;
1463 // All succeeding offsets have the current size value added in, fix this.
1464 if (CPEBB->empty()) {
1465 BBInfo[CPEBB->getNumber()].Size = 0;
1467 // This block no longer needs to be aligned.
1468 CPEBB->setAlignment(0);
1470 // Entries are sorted by descending alignment, so realign from the front.
1471 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1473 adjustBBOffsetsAfter(CPEBB);
1474 // An island has only one predecessor BB and one successor BB. Check if
1475 // this BB's predecessor jumps directly to this BB's successor. This
1476 // shouldn't happen currently.
1477 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1478 // FIXME: remove the empty blocks after all the work is done?
1481 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1483 bool MipsConstantIslands::removeUnusedCPEntries() {
1484 unsigned MadeChange = false;
1485 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1486 std::vector<CPEntry> &CPEs = CPEntries[i];
1487 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1488 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1489 removeDeadCPEMI(CPEs[j].CPEMI);
1490 CPEs[j].CPEMI = nullptr;
1498 /// isBBInRange - Returns true if the distance between specific MI and
1499 /// specific BB can fit in MI's displacement field.
1500 bool MipsConstantIslands::isBBInRange
1501 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1505 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1506 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1508 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1509 << " from BB#" << MI->getParent()->getNumber()
1510 << " max delta=" << MaxDisp
1511 << " from " << getOffsetOf(MI) << " to " << DestOffset
1512 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1514 if (BrOffset <= DestOffset) {
1515 // Branch before the Dest.
1516 if (DestOffset-BrOffset <= MaxDisp)
1519 if (BrOffset-DestOffset <= MaxDisp)
1525 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1526 /// away to fit in its displacement field.
1527 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1528 MachineInstr *MI = Br.MI;
1529 unsigned TargetOperand = branchTargetOperand(MI);
1530 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1532 // Check to see if the DestBB is already in-range.
1533 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1537 return fixupUnconditionalBr(Br);
1538 return fixupConditionalBr(Br);
1541 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1542 /// too far away to fit in its displacement field. If the LR register has been
1543 /// spilled in the epilogue, then we can use BL to implement a far jump.
1544 /// Otherwise, add an intermediate branch instruction to a branch.
1546 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1547 MachineInstr *MI = Br.MI;
1548 MachineBasicBlock *MBB = MI->getParent();
1549 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1550 // Use BL to implement far jump.
1551 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1552 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1553 Br.MaxDisp = BimmX16MaxDisp;
1554 MI->setDesc(TII->get(Mips::BimmX16));
1557 // need to give the math a more careful look here
1558 // this is really a segment address and not
1559 // a PC relative address. FIXME. But I think that
1560 // just reducing the bits by 1 as I've done is correct.
1561 // The basic block we are branching too much be longword aligned.
1562 // we know that RA is saved because we always save it right now.
1563 // this requirement will be relaxed later but we also have an alternate
1564 // way to implement this that I will implement that does not need jal.
1565 // We should have a way to back out this alignment restriction if we "can" later.
1566 // but it is not harmful.
1568 DestBB->setAlignment(2);
1569 Br.MaxDisp = ((1<<24)-1) * 2;
1570 MI->setDesc(TII->get(Mips::JalB16));
1572 BBInfo[MBB->getNumber()].Size += 2;
1573 adjustBBOffsetsAfter(MBB);
1577 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1583 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1584 /// far away to fit in its displacement field. It is converted to an inverse
1585 /// conditional branch + an unconditional branch to the destination.
1587 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1588 MachineInstr *MI = Br.MI;
1589 unsigned TargetOperand = branchTargetOperand(MI);
1590 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1591 unsigned Opcode = MI->getOpcode();
1592 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1593 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1595 // Check to see if the DestBB is already in-range.
1596 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1597 Br.MaxDisp = LongFormMaxOff;
1598 MI->setDesc(TII->get(LongFormOpcode));
1602 // Add an unconditional branch to the destination and invert the branch
1603 // condition to jump over it:
1610 // If the branch is at the end of its MBB and that has a fall-through block,
1611 // direct the updated conditional branch to the fall-through block. Otherwise,
1612 // split the MBB before the next instruction.
1613 MachineBasicBlock *MBB = MI->getParent();
1614 MachineInstr *BMI = &MBB->back();
1615 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1616 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1620 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1621 isUnconditionalBranch(BMI->getOpcode())) {
1622 // Last MI in the BB is an unconditional branch. Can we simply invert the
1623 // condition and swap destinations:
1629 unsigned BMITargetOperand = branchTargetOperand(BMI);
1630 MachineBasicBlock *NewDest =
1631 BMI->getOperand(BMITargetOperand).getMBB();
1632 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1633 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1635 MI->setDesc(TII->get(OppositeBranchOpcode));
1636 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1637 MI->getOperand(TargetOperand).setMBB(NewDest);
1645 splitBlockBeforeInstr(MI);
1646 // No need for the branch to the next block. We're adding an unconditional
1647 // branch to the destination.
1648 int delta = TII->GetInstSizeInBytes(&MBB->back());
1649 BBInfo[MBB->getNumber()].Size -= delta;
1650 MBB->back().eraseFromParent();
1651 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1653 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1655 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1656 << " also invert condition and change dest. to BB#"
1657 << NextBB->getNumber() << "\n");
1659 // Insert a new conditional branch and a new unconditional branch.
1660 // Also update the ImmBranch as well as adding a new entry for the new branch.
1661 if (MI->getNumExplicitOperands() == 2) {
1662 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1663 .addReg(MI->getOperand(0).getReg())
1666 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1669 Br.MI = &MBB->back();
1670 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1671 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1672 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1673 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1674 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1676 // Remove the old conditional branch. It may or may not still be in MBB.
1677 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1678 MI->eraseFromParent();
1679 adjustBBOffsetsAfter(MBB);
1684 void MipsConstantIslands::prescanForConstants() {
1687 for (MachineFunction::iterator B =
1688 MF->begin(), E = MF->end(); B != E; ++B) {
1689 for (MachineBasicBlock::instr_iterator I =
1690 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1691 switch(I->getDesc().getOpcode()) {
1692 case Mips::LwConstant32: {
1693 PrescannedForConstants = true;
1694 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1695 J = I->getNumOperands();
1696 DEBUG(dbgs() << "num operands " << J << "\n");
1697 MachineOperand& Literal = I->getOperand(1);
1698 if (Literal.isImm()) {
1699 int64_t V = Literal.getImm();
1700 DEBUG(dbgs() << "literal " << V << "\n");
1702 Type::getInt32Ty(MF->getFunction()->getContext());
1703 const Constant *C = ConstantInt::get(Int32Ty, V);
1704 unsigned index = MCP->getConstantPoolIndex(C, 4);
1705 I->getOperand(2).ChangeToImmediate(index);
1706 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1707 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1708 I->RemoveOperand(1);
1709 I->RemoveOperand(1);
1710 I->addOperand(MachineOperand::CreateCPI(index, 0));
1711 I->addOperand(MachineOperand::CreateImm(4));