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
24 #define DEBUG_TYPE "mips-constant-islands"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "Mips16InstrInfo.h"
29 #include "MipsMachineFunction.h"
30 #include "MipsTargetMachine.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/InstIterator.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Support/Format.h"
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 unsigned int longformBranchOpcode(unsigned int Opcode) {
103 return Mips::BimmX16;
106 return Mips::BteqzX16;
109 return Mips::BtnezX16;
112 case Mips::BeqzRxImm16:
113 case Mips::BeqzRxImmX16:
114 return Mips::BeqzRxImmX16;
115 case Mips::BnezRxImm16:
116 case Mips::BnezRxImmX16:
117 return Mips::BnezRxImmX16;
119 llvm_unreachable("Unknown branch type");
123 // FIXME: need to go through this whole constant islands port and check the math
124 // for branch ranges and clean this up and make some functions to calculate things
125 // that are done many times identically.
126 // Need to refactor some of the code to call this routine.
128 static unsigned int branchMaxOffsets(unsigned int Opcode) {
129 unsigned Bits, Scale;
139 case Mips::BeqzRxImm16:
143 case Mips::BeqzRxImmX16:
147 case Mips::BnezRxImm16:
151 case Mips::BnezRxImmX16:
172 llvm_unreachable("Unknown branch type");
174 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
181 typedef MachineBasicBlock::iterator Iter;
182 typedef MachineBasicBlock::reverse_iterator ReverseIter;
184 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
185 /// requires constant pool entries to be scattered among the instructions
186 /// inside a function. To do this, it completely ignores the normal LLVM
187 /// constant pool; instead, it places constants wherever it feels like with
188 /// special instructions.
190 /// The terminology used in this pass includes:
191 /// Islands - Clumps of constants placed in the function.
192 /// Water - Potential places where an island could be formed.
193 /// CPE - A constant pool entry that has been placed somewhere, which
194 /// tracks a list of users.
196 class MipsConstantIslands : public MachineFunctionPass {
198 /// BasicBlockInfo - Information about the offset and size of a single
200 struct BasicBlockInfo {
201 /// Offset - Distance from the beginning of the function to the beginning
202 /// of this basic block.
204 /// Offsets are computed assuming worst case padding before an aligned
205 /// block. This means that subtracting basic block offsets always gives a
206 /// conservative estimate of the real distance which may be smaller.
208 /// Because worst case padding is used, the computed offset of an aligned
209 /// block may not actually be aligned.
212 /// Size - Size of the basic block in bytes. If the block contains
213 /// inline assembly, this is a worst case estimate.
215 /// The size does not include any alignment padding whether from the
216 /// beginning of the block, or from an aligned jump table at the end.
219 // FIXME: ignore LogAlign for this patch
221 unsigned postOffset(unsigned LogAlign = 0) const {
222 unsigned PO = Offset + Size;
226 BasicBlockInfo() : Offset(0), Size(0) {}
230 std::vector<BasicBlockInfo> BBInfo;
232 /// WaterList - A sorted list of basic blocks where islands could be placed
233 /// (i.e. blocks that don't fall through to the following block, due
234 /// to a return, unreachable, or unconditional branch).
235 std::vector<MachineBasicBlock*> WaterList;
237 /// NewWaterList - The subset of WaterList that was created since the
238 /// previous iteration by inserting unconditional branches.
239 SmallSet<MachineBasicBlock*, 4> NewWaterList;
241 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
243 /// CPUser - One user of a constant pool, keeping the machine instruction
244 /// pointer, the constant pool being referenced, and the max displacement
245 /// allowed from the instruction to the CP. The HighWaterMark records the
246 /// highest basic block where a new CPEntry can be placed. To ensure this
247 /// pass terminates, the CP entries are initially placed at the end of the
248 /// function and then move monotonically to lower addresses. The
249 /// exception to this rule is when the current CP entry for a particular
250 /// CPUser is out of range, but there is another CP entry for the same
251 /// constant value in range. We want to use the existing in-range CP
252 /// entry, but if it later moves out of range, the search for new water
253 /// should resume where it left off. The HighWaterMark is used to record
258 MachineBasicBlock *HighWaterMark;
261 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
262 // with different displacements
263 unsigned LongFormOpcode;
266 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
268 unsigned longformmaxdisp, unsigned longformopcode)
269 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
270 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
272 HighWaterMark = CPEMI->getParent();
274 /// getMaxDisp - Returns the maximum displacement supported by MI.
275 unsigned getMaxDisp() const {
276 unsigned xMaxDisp = ConstantIslandsSmallOffset?
277 ConstantIslandsSmallOffset: MaxDisp;
280 void setMaxDisp(unsigned val) {
283 unsigned getLongFormMaxDisp() const {
284 return LongFormMaxDisp;
286 unsigned getLongFormOpcode() const {
287 return LongFormOpcode;
291 /// CPUsers - Keep track of all of the machine instructions that use various
292 /// constant pools and their max displacement.
293 std::vector<CPUser> CPUsers;
295 /// CPEntry - One per constant pool entry, keeping the machine instruction
296 /// pointer, the constpool index, and the number of CPUser's which
297 /// reference this entry.
302 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
303 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
306 /// CPEntries - Keep track of all of the constant pool entry machine
307 /// instructions. For each original constpool index (i.e. those that
308 /// existed upon entry to this pass), it keeps a vector of entries.
309 /// Original elements are cloned as we go along; the clones are
310 /// put in the vector of the original element, but have distinct CPIs.
311 std::vector<std::vector<CPEntry> > CPEntries;
313 /// ImmBranch - One per immediate branch, keeping the machine instruction
314 /// pointer, conditional or unconditional, the max displacement,
315 /// and (if isCond is true) the corresponding unconditional branch
319 unsigned MaxDisp : 31;
322 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
323 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
326 /// ImmBranches - Keep track of all the immediate branch instructions.
328 std::vector<ImmBranch> ImmBranches;
330 /// HasFarJump - True if any far jump instruction has been emitted during
331 /// the branch fix up pass.
334 const TargetMachine &TM;
337 const MipsSubtarget *STI;
338 const Mips16InstrInfo *TII;
339 MipsFunctionInfo *MFI;
341 MachineConstantPool *MCP;
343 unsigned PICLabelUId;
344 bool PrescannedForConstants;
346 void initPICLabelUId(unsigned UId) {
351 unsigned createPICLabelUId() {
352 return PICLabelUId++;
357 MipsConstantIslands(TargetMachine &tm)
358 : MachineFunctionPass(ID), TM(tm),
359 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
360 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
361 STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
362 PrescannedForConstants(false){}
364 virtual const char *getPassName() const {
365 return "Mips Constant Islands";
368 bool runOnMachineFunction(MachineFunction &F);
370 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
371 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
372 unsigned getCPELogAlign(const MachineInstr *CPEMI);
373 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
374 unsigned getOffsetOf(MachineInstr *MI) const;
375 unsigned getUserOffset(CPUser&) const;
379 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
380 unsigned Disp, bool NegativeOK);
381 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
384 bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
387 void computeBlockSize(MachineBasicBlock *MBB);
388 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
389 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
390 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
391 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
392 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
393 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
394 bool findAvailableWater(CPUser&U, unsigned UserOffset,
395 water_iterator &WaterIter);
396 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
397 MachineBasicBlock *&NewMBB);
398 bool handleConstantPoolUser(unsigned CPUserIndex);
399 void removeDeadCPEMI(MachineInstr *CPEMI);
400 bool removeUnusedCPEntries();
401 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
402 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
403 bool DoDump = false);
404 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
405 CPUser &U, unsigned &Growth);
406 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
407 bool fixupImmediateBr(ImmBranch &Br);
408 bool fixupConditionalBr(ImmBranch &Br);
409 bool fixupUnconditionalBr(ImmBranch &Br);
411 void prescanForConstants();
417 char MipsConstantIslands::ID = 0;
418 } // end of anonymous namespace
421 bool MipsConstantIslands::isLongFormOffsetInRange
422 (unsigned UserOffset, unsigned TrialOffset,
424 return isOffsetInRange(UserOffset, TrialOffset,
425 U.getLongFormMaxDisp(), U.NegOk);
428 bool MipsConstantIslands::isOffsetInRange
429 (unsigned UserOffset, unsigned TrialOffset,
431 return isOffsetInRange(UserOffset, TrialOffset,
432 U.getMaxDisp(), U.NegOk);
434 /// print block size and offset information - debugging
435 void MipsConstantIslands::dumpBBs() {
437 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
438 const BasicBlockInfo &BBI = BBInfo[J];
439 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
440 << format(" size=%#x\n", BBInfo[J].Size);
444 /// createMipsLongBranchPass - Returns a pass that converts branches to long
446 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
447 return new MipsConstantIslands(tm);
450 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
451 // The intention is for this to be a mips16 only pass for now
454 MCP = mf.getConstantPool();
455 DEBUG(dbgs() << "constant island machine function " << "\n");
456 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
457 !MipsSubtarget::useConstantIslands()) {
460 TII = (const Mips16InstrInfo*)MF->getTarget().getInstrInfo();
461 MFI = MF->getInfo<MipsFunctionInfo>();
462 DEBUG(dbgs() << "constant island processing " << "\n");
464 // will need to make predermination if there is any constants we need to
465 // put in constant islands. TBD.
467 if (!PrescannedForConstants) prescanForConstants();
470 // This pass invalidates liveness information when it splits basic blocks.
471 MF->getRegInfo().invalidateLiveness();
473 // Renumber all of the machine basic blocks in the function, guaranteeing that
474 // the numbers agree with the position of the block in the function.
475 MF->RenumberBlocks();
477 bool MadeChange = false;
479 // Perform the initial placement of the constant pool entries. To start with,
480 // we put them all at the end of the function.
481 std::vector<MachineInstr*> CPEMIs;
483 doInitialPlacement(CPEMIs);
485 /// The next UID to take is the first unused one.
486 initPICLabelUId(CPEMIs.size());
488 // Do the initial scan of the function, building up information about the
489 // sizes of each block, the location of all the water, and finding all of the
490 // constant pool users.
491 initializeFunctionInfo(CPEMIs);
495 /// Remove dead constant pool entries.
496 MadeChange |= removeUnusedCPEntries();
498 // Iteratively place constant pool entries and fix up branches until there
500 unsigned NoCPIters = 0, NoBRIters = 0;
503 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
504 bool CPChange = false;
505 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
506 CPChange |= handleConstantPoolUser(i);
507 if (CPChange && ++NoCPIters > 30)
508 report_fatal_error("Constant Island pass failed to converge!");
511 // Clear NewWaterList now. If we split a block for branches, it should
512 // appear as "new water" for the next iteration of constant pool placement.
513 NewWaterList.clear();
515 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
516 bool BRChange = false;
517 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
518 BRChange |= fixupImmediateBr(ImmBranches[i]);
519 if (BRChange && ++NoBRIters > 30)
520 report_fatal_error("Branch Fix Up pass failed to converge!");
522 if (!CPChange && !BRChange)
527 DEBUG(dbgs() << '\n'; dumpBBs());
537 /// doInitialPlacement - Perform the initial placement of the constant pool
538 /// entries. To start with, we put them all at the end of the function.
540 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
541 // Create the basic block to hold the CPE's.
542 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
546 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
547 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
549 // Mark the basic block as required by the const-pool.
550 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
551 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
553 // The function needs to be as aligned as the basic blocks. The linker may
554 // move functions around based on their alignment.
555 MF->ensureAlignment(BB->getAlignment());
557 // Order the entries in BB by descending alignment. That ensures correct
558 // alignment of all entries as long as BB is sufficiently aligned. Keep
559 // track of the insertion point for each alignment. We are going to bucket
560 // sort the entries as they are created.
561 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
563 // Add all of the constants from the constant pool to the end block, use an
564 // identity mapping of CPI's to CPE's.
565 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
567 const DataLayout &TD = *MF->getTarget().getDataLayout();
568 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
569 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
570 assert(Size >= 4 && "Too small constant pool entry");
571 unsigned Align = CPs[i].getAlignment();
572 assert(isPowerOf2_32(Align) && "Invalid alignment");
573 // Verify that all constant pool entries are a multiple of their alignment.
574 // If not, we would have to pad them out so that instructions stay aligned.
575 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
577 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
578 unsigned LogAlign = Log2_32(Align);
579 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
581 MachineInstr *CPEMI =
582 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
583 .addImm(i).addConstantPoolIndex(i).addImm(Size);
585 CPEMIs.push_back(CPEMI);
587 // Ensure that future entries with higher alignment get inserted before
588 // CPEMI. This is bucket sort with iterators.
589 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
590 if (InsPoint[a] == InsAt)
592 // Add a new CPEntry, but no corresponding CPUser yet.
593 std::vector<CPEntry> CPEs;
594 CPEs.push_back(CPEntry(CPEMI, i));
595 CPEntries.push_back(CPEs);
597 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
598 << Size << ", align = " << Align <<'\n');
603 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
604 /// into the block immediately after it.
605 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
606 // Get the next machine basic block in the function.
607 MachineFunction::iterator MBBI = MBB;
608 // Can't fall off end of function.
609 if (llvm::next(MBBI) == MBB->getParent()->end())
612 MachineBasicBlock *NextBB = llvm::next(MBBI);
613 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
614 E = MBB->succ_end(); I != E; ++I)
621 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
622 /// look up the corresponding CPEntry.
623 MipsConstantIslands::CPEntry
624 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
625 const MachineInstr *CPEMI) {
626 std::vector<CPEntry> &CPEs = CPEntries[CPI];
627 // Number of entries per constpool index should be small, just do a
629 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
630 if (CPEs[i].CPEMI == CPEMI)
636 /// getCPELogAlign - Returns the required alignment of the constant pool entry
637 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
638 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
639 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
641 // Everything is 4-byte aligned unless AlignConstantIslands is set.
642 if (!AlignConstantIslands)
645 unsigned CPI = CPEMI->getOperand(1).getIndex();
646 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
647 unsigned Align = MCP->getConstants()[CPI].getAlignment();
648 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
649 return Log2_32(Align);
652 /// initializeFunctionInfo - Do the initial scan of the function, building up
653 /// information about the sizes of each block, the location of all the water,
654 /// and finding all of the constant pool users.
655 void MipsConstantIslands::
656 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
658 BBInfo.resize(MF->getNumBlockIDs());
660 // First thing, compute the size of all basic blocks, and see if the function
661 // has any inline assembly in it. If so, we have to be conservative about
662 // alignment assumptions, as we don't know for sure the size of any
663 // instructions in the inline assembly.
664 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
668 // Compute block offsets.
669 adjustBBOffsetsAfter(MF->begin());
671 // Now go back through the instructions and build up our data structures.
672 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
674 MachineBasicBlock &MBB = *MBBI;
676 // If this block doesn't fall through into the next MBB, then this is
677 // 'water' that a constant pool island could be placed.
678 if (!BBHasFallthrough(&MBB))
679 WaterList.push_back(&MBB);
680 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
682 if (I->isDebugValue())
685 int Opc = I->getOpcode();
693 continue; // Ignore other branches for now
704 case Mips::BeqzRxImm16:
709 case Mips::BeqzRxImmX16:
714 case Mips::BnezRxImm16:
719 case Mips::BnezRxImmX16:
745 // Record this immediate branch.
746 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
747 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
750 if (Opc == Mips::CONSTPOOL_ENTRY)
754 // Scan the instructions for constant pool operands.
755 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
756 if (I->getOperand(op).isCPI()) {
758 // We found one. The addressing mode tells us the max displacement
759 // from the PC that this instruction permits.
761 // Basic size info comes from the TSFlags field.
765 unsigned LongFormBits = 0;
766 unsigned LongFormScale = 0;
767 unsigned LongFormOpcode = 0;
770 llvm_unreachable("Unknown addressing mode for CP reference!");
771 case Mips::LwRxPcTcp16:
774 LongFormOpcode = Mips::LwRxPcTcpX16;
778 case Mips::LwRxPcTcpX16:
784 // Remember that this is a user of a CP entry.
785 unsigned CPI = I->getOperand(op).getIndex();
786 MachineInstr *CPEMI = CPEMIs[CPI];
787 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
788 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
789 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
790 LongFormMaxOffs, LongFormOpcode));
792 // Increment corresponding CPEntry reference count.
793 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
794 assert(CPE && "Cannot find a corresponding CPEntry!");
797 // Instructions can only use one CP entry, don't bother scanning the
798 // rest of the operands.
808 /// computeBlockSize - Compute the size and some alignment information for MBB.
809 /// This function updates BBInfo directly.
810 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
811 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
814 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
816 BBI.Size += TII->GetInstSizeInBytes(I);
820 /// getOffsetOf - Return the current offset of the specified machine instruction
821 /// from the start of the function. This offset changes as stuff is moved
822 /// around inside the function.
823 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
824 MachineBasicBlock *MBB = MI->getParent();
826 // The offset is composed of two things: the sum of the sizes of all MBB's
827 // before this instruction's block, and the offset from the start of the block
829 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
831 // Sum instructions before MI in MBB.
832 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
833 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
834 Offset += TII->GetInstSizeInBytes(I);
839 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
841 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
842 const MachineBasicBlock *RHS) {
843 return LHS->getNumber() < RHS->getNumber();
846 /// updateForInsertedWaterBlock - When a block is newly inserted into the
847 /// machine function, it upsets all of the block numbers. Renumber the blocks
848 /// and update the arrays that parallel this numbering.
849 void MipsConstantIslands::updateForInsertedWaterBlock
850 (MachineBasicBlock *NewBB) {
851 // Renumber the MBB's to keep them consecutive.
852 NewBB->getParent()->RenumberBlocks(NewBB);
854 // Insert an entry into BBInfo to align it properly with the (newly
855 // renumbered) block numbers.
856 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
858 // Next, update WaterList. Specifically, we need to add NewMBB as having
859 // available water after it.
861 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
863 WaterList.insert(IP, NewBB);
866 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
867 return getOffsetOf(U.MI);
870 /// Split the basic block containing MI into two blocks, which are joined by
871 /// an unconditional branch. Update data structures and renumber blocks to
872 /// account for this change and returns the newly created block.
873 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
875 MachineBasicBlock *OrigBB = MI->getParent();
877 // Create a new MBB for the code after the OrigBB.
878 MachineBasicBlock *NewBB =
879 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
880 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
881 MF->insert(MBBI, NewBB);
883 // Splice the instructions starting with MI over to NewBB.
884 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
886 // Add an unconditional branch from OrigBB to NewBB.
887 // Note the new unconditional branch is not being recorded.
888 // There doesn't seem to be meaningful DebugInfo available; this doesn't
889 // correspond to anything in the source.
890 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
893 // Update the CFG. All succs of OrigBB are now succs of NewBB.
894 NewBB->transferSuccessors(OrigBB);
896 // OrigBB branches to NewBB.
897 OrigBB->addSuccessor(NewBB);
899 // Update internal data structures to account for the newly inserted MBB.
900 // This is almost the same as updateForInsertedWaterBlock, except that
901 // the Water goes after OrigBB, not NewBB.
902 MF->RenumberBlocks(NewBB);
904 // Insert an entry into BBInfo to align it properly with the (newly
905 // renumbered) block numbers.
906 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
908 // Next, update WaterList. Specifically, we need to add OrigMBB as having
909 // available water after it (but not if it's already there, which happens
910 // when splitting before a conditional branch that is followed by an
911 // unconditional branch - in that case we want to insert NewBB).
913 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
915 MachineBasicBlock* WaterBB = *IP;
916 if (WaterBB == OrigBB)
917 WaterList.insert(llvm::next(IP), NewBB);
919 WaterList.insert(IP, OrigBB);
920 NewWaterList.insert(OrigBB);
922 // Figure out how large the OrigBB is. As the first half of the original
923 // block, it cannot contain a tablejump. The size includes
924 // the new jump we added. (It should be possible to do this without
925 // recounting everything, but it's very confusing, and this is rarely
927 computeBlockSize(OrigBB);
929 // Figure out how large the NewMBB is. As the second half of the original
930 // block, it may contain a tablejump.
931 computeBlockSize(NewBB);
933 // All BBOffsets following these blocks must be modified.
934 adjustBBOffsetsAfter(OrigBB);
941 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
942 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
943 /// constant pool entry).
944 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
945 unsigned TrialOffset, unsigned MaxDisp,
947 if (UserOffset <= TrialOffset) {
948 // User before the Trial.
949 if (TrialOffset - UserOffset <= MaxDisp)
951 } else if (NegativeOK) {
952 if (UserOffset - TrialOffset <= MaxDisp)
958 /// isWaterInRange - Returns true if a CPE placed after the specified
959 /// Water (a basic block) will be in range for the specific MI.
961 /// Compute how much the function will grow by inserting a CPE after Water.
962 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
963 MachineBasicBlock* Water, CPUser &U,
965 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
966 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
967 unsigned NextBlockOffset, NextBlockAlignment;
968 MachineFunction::const_iterator NextBlock = Water;
969 if (++NextBlock == MF->end()) {
970 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
971 NextBlockAlignment = 0;
973 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
974 NextBlockAlignment = NextBlock->getAlignment();
976 unsigned Size = U.CPEMI->getOperand(2).getImm();
977 unsigned CPEEnd = CPEOffset + Size;
979 // The CPE may be able to hide in the alignment padding before the next
980 // block. It may also cause more padding to be required if it is more aligned
981 // that the next block.
982 if (CPEEnd > NextBlockOffset) {
983 Growth = CPEEnd - NextBlockOffset;
984 // Compute the padding that would go at the end of the CPE to align the next
986 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
988 // If the CPE is to be inserted before the instruction, that will raise
989 // the offset of the instruction. Also account for unknown alignment padding
990 // in blocks between CPE and the user.
991 if (CPEOffset < UserOffset)
992 UserOffset += Growth;
994 // CPE fits in existing padding.
997 return isOffsetInRange(UserOffset, CPEOffset, U);
1000 /// isCPEntryInRange - Returns true if the distance between specific MI and
1001 /// specific ConstPool entry instruction can fit in MI's displacement field.
1002 bool MipsConstantIslands::isCPEntryInRange
1003 (MachineInstr *MI, unsigned UserOffset,
1004 MachineInstr *CPEMI, unsigned MaxDisp,
1005 bool NegOk, bool DoDump) {
1006 unsigned CPEOffset = getOffsetOf(CPEMI);
1010 unsigned Block = MI->getParent()->getNumber();
1011 const BasicBlockInfo &BBI = BBInfo[Block];
1012 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1013 << " max delta=" << MaxDisp
1014 << format(" insn address=%#x", UserOffset)
1015 << " in BB#" << Block << ": "
1016 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1017 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1018 int(CPEOffset-UserOffset));
1022 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1026 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1027 /// unconditionally branches to its only successor.
1028 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1029 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1031 MachineBasicBlock *Succ = *MBB->succ_begin();
1032 MachineBasicBlock *Pred = *MBB->pred_begin();
1033 MachineInstr *PredMI = &Pred->back();
1034 if (PredMI->getOpcode() == Mips::Bimm16)
1035 return PredMI->getOperand(0).getMBB() == Succ;
1040 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1041 unsigned BBNum = BB->getNumber();
1042 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1043 // Get the offset and known bits at the end of the layout predecessor.
1044 // Include the alignment of the current block.
1045 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1046 BBInfo[i].Offset = Offset;
1050 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1051 /// and instruction CPEMI, and decrement its refcount. If the refcount
1052 /// becomes 0 remove the entry and instruction. Returns true if we removed
1053 /// the entry, false if we didn't.
1055 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1056 MachineInstr *CPEMI) {
1057 // Find the old entry. Eliminate it if it is no longer used.
1058 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1059 assert(CPE && "Unexpected!");
1060 if (--CPE->RefCount == 0) {
1061 removeDeadCPEMI(CPEMI);
1069 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1070 /// if not, see if an in-range clone of the CPE is in range, and if so,
1071 /// change the data structures so the user references the clone. Returns:
1072 /// 0 = no existing entry found
1073 /// 1 = entry found, and there were no code insertions or deletions
1074 /// 2 = entry found, and there were code insertions or deletions
1075 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1077 MachineInstr *UserMI = U.MI;
1078 MachineInstr *CPEMI = U.CPEMI;
1080 // Check to see if the CPE is already in-range.
1081 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1083 DEBUG(dbgs() << "In range\n");
1087 // No. Look for previously created clones of the CPE that are in range.
1088 unsigned CPI = CPEMI->getOperand(1).getIndex();
1089 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1090 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1091 // We already tried this one
1092 if (CPEs[i].CPEMI == CPEMI)
1094 // Removing CPEs can leave empty entries, skip
1095 if (CPEs[i].CPEMI == NULL)
1097 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1099 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1100 << CPEs[i].CPI << "\n");
1101 // Point the CPUser node to the replacement
1102 U.CPEMI = CPEs[i].CPEMI;
1103 // Change the CPI in the instruction operand to refer to the clone.
1104 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1105 if (UserMI->getOperand(j).isCPI()) {
1106 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1109 // Adjust the refcount of the clone...
1111 // ...and the original. If we didn't remove the old entry, none of the
1112 // addresses changed, so we don't need another pass.
1113 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1119 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1120 /// This version checks if the longer form of the instruction can be used to
1121 /// to satisfy things.
1122 /// if not, see if an in-range clone of the CPE is in range, and if so,
1123 /// change the data structures so the user references the clone. Returns:
1124 /// 0 = no existing entry found
1125 /// 1 = entry found, and there were no code insertions or deletions
1126 /// 2 = entry found, and there were code insertions or deletions
1127 int MipsConstantIslands::findLongFormInRangeCPEntry
1128 (CPUser& U, unsigned UserOffset)
1130 MachineInstr *UserMI = U.MI;
1131 MachineInstr *CPEMI = U.CPEMI;
1133 // Check to see if the CPE is already in-range.
1134 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1135 U.getLongFormMaxDisp(), U.NegOk,
1137 DEBUG(dbgs() << "In range\n");
1138 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1139 U.setMaxDisp(U.getLongFormMaxDisp());
1140 return 2; // instruction is longer length now
1143 // No. Look for previously created clones of the CPE that are in range.
1144 unsigned CPI = CPEMI->getOperand(1).getIndex();
1145 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1146 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1147 // We already tried this one
1148 if (CPEs[i].CPEMI == CPEMI)
1150 // Removing CPEs can leave empty entries, skip
1151 if (CPEs[i].CPEMI == NULL)
1153 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1154 U.getLongFormMaxDisp(), U.NegOk)) {
1155 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1156 << CPEs[i].CPI << "\n");
1157 // Point the CPUser node to the replacement
1158 U.CPEMI = CPEs[i].CPEMI;
1159 // Change the CPI in the instruction operand to refer to the clone.
1160 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1161 if (UserMI->getOperand(j).isCPI()) {
1162 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1165 // Adjust the refcount of the clone...
1167 // ...and the original. If we didn't remove the old entry, none of the
1168 // addresses changed, so we don't need another pass.
1169 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1175 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1176 /// the specific unconditional branch instruction.
1177 static inline unsigned getUnconditionalBrDisp(int Opc) {
1180 return ((1<<10)-1)*2;
1182 return ((1<<16)-1)*2;
1186 return ((1<<16)-1)*2;
1189 /// findAvailableWater - Look for an existing entry in the WaterList in which
1190 /// we can place the CPE referenced from U so it's within range of U's MI.
1191 /// Returns true if found, false if not. If it returns true, WaterIter
1192 /// is set to the WaterList entry.
1193 /// To ensure that this pass
1194 /// terminates, the CPE location for a particular CPUser is only allowed to
1195 /// move to a lower address, so search backward from the end of the list and
1196 /// prefer the first water that is in range.
1197 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1198 water_iterator &WaterIter) {
1199 if (WaterList.empty())
1202 unsigned BestGrowth = ~0u;
1203 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1205 MachineBasicBlock* WaterBB = *IP;
1206 // Check if water is in range and is either at a lower address than the
1207 // current "high water mark" or a new water block that was created since
1208 // the previous iteration by inserting an unconditional branch. In the
1209 // latter case, we want to allow resetting the high water mark back to
1210 // this new water since we haven't seen it before. Inserting branches
1211 // should be relatively uncommon and when it does happen, we want to be
1212 // sure to take advantage of it for all the CPEs near that block, so that
1213 // we don't insert more branches than necessary.
1215 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1216 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1217 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1218 // This is the least amount of required padding seen so far.
1219 BestGrowth = Growth;
1221 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1222 << " Growth=" << Growth << '\n');
1224 // Keep looking unless it is perfect.
1225 if (BestGrowth == 0)
1231 return BestGrowth != ~0u;
1234 /// createNewWater - No existing WaterList entry will work for
1235 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1236 /// block is used if in range, and the conditional branch munged so control
1237 /// flow is correct. Otherwise the block is split to create a hole with an
1238 /// unconditional branch around it. In either case NewMBB is set to a
1239 /// block following which the new island can be inserted (the WaterList
1240 /// is not adjusted).
1241 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1242 unsigned UserOffset,
1243 MachineBasicBlock *&NewMBB) {
1244 CPUser &U = CPUsers[CPUserIndex];
1245 MachineInstr *UserMI = U.MI;
1246 MachineInstr *CPEMI = U.CPEMI;
1247 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1248 MachineBasicBlock *UserMBB = UserMI->getParent();
1249 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1251 // If the block does not end in an unconditional branch already, and if the
1252 // end of the block is within range, make new water there.
1253 if (BBHasFallthrough(UserMBB)) {
1254 // Size of branch to insert.
1256 // Compute the offset where the CPE will begin.
1257 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1259 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1260 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1261 << format(", expected CPE offset %#x\n", CPEOffset));
1262 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1263 // Add an unconditional branch from UserMBB to fallthrough block. Record
1264 // it for branch lengthening; this new branch will not get out of range,
1265 // but if the preceding conditional branch is out of range, the targets
1266 // will be exchanged, and the altered branch may be out of range, so the
1267 // machinery has to know about it.
1268 int UncondBr = Mips::Bimm16;
1269 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1270 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1271 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1272 MaxDisp, false, UncondBr));
1273 BBInfo[UserMBB->getNumber()].Size += Delta;
1274 adjustBBOffsetsAfter(UserMBB);
1279 // What a big block. Find a place within the block to split it.
1281 // Try to split the block so it's fully aligned. Compute the latest split
1282 // point where we can add a 4-byte branch instruction, and then align to
1283 // LogAlign which is the largest possible alignment in the function.
1284 unsigned LogAlign = MF->getAlignment();
1285 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1286 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1287 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1290 // The 4 in the following is for the unconditional branch we'll be inserting
1291 // Alignment of the island is handled
1292 // inside isOffsetInRange.
1293 BaseInsertOffset -= 4;
1295 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1296 << " la=" << LogAlign << '\n');
1298 // This could point off the end of the block if we've already got constant
1299 // pool entries following this block; only the last one is in the water list.
1300 // Back past any possible branches (allow for a conditional and a maximally
1301 // long unconditional).
1302 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1303 BaseInsertOffset = UserBBI.postOffset() - 8;
1304 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1306 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1307 CPEMI->getOperand(2).getImm();
1308 MachineBasicBlock::iterator MI = UserMI;
1310 unsigned CPUIndex = CPUserIndex+1;
1311 unsigned NumCPUsers = CPUsers.size();
1312 //MachineInstr *LastIT = 0;
1313 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1314 Offset < BaseInsertOffset;
1315 Offset += TII->GetInstSizeInBytes(MI),
1316 MI = llvm::next(MI)) {
1317 assert(MI != UserMBB->end() && "Fell off end of block");
1318 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1319 CPUser &U = CPUsers[CPUIndex];
1320 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1321 // Shift intertion point by one unit of alignment so it is within reach.
1322 BaseInsertOffset -= 1u << LogAlign;
1323 EndInsertOffset -= 1u << LogAlign;
1325 // This is overly conservative, as we don't account for CPEMIs being
1326 // reused within the block, but it doesn't matter much. Also assume CPEs
1327 // are added in order with alignment padding. We may eventually be able
1328 // to pack the aligned CPEs better.
1329 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1335 NewMBB = splitBlockBeforeInstr(MI);
1338 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1339 /// is out-of-range. If so, pick up the constant pool value and move it some
1340 /// place in-range. Return true if we changed any addresses (thus must run
1341 /// another pass of branch lengthening), false otherwise.
1342 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1343 CPUser &U = CPUsers[CPUserIndex];
1344 MachineInstr *UserMI = U.MI;
1345 MachineInstr *CPEMI = U.CPEMI;
1346 unsigned CPI = CPEMI->getOperand(1).getIndex();
1347 unsigned Size = CPEMI->getOperand(2).getImm();
1348 // Compute this only once, it's expensive.
1349 unsigned UserOffset = getUserOffset(U);
1351 // See if the current entry is within range, or there is a clone of it
1353 int result = findInRangeCPEntry(U, UserOffset);
1354 if (result==1) return false;
1355 else if (result==2) return true;
1358 // Look for water where we can place this CPE.
1359 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1360 MachineBasicBlock *NewMBB;
1362 if (findAvailableWater(U, UserOffset, IP)) {
1363 DEBUG(dbgs() << "Found water in range\n");
1364 MachineBasicBlock *WaterBB = *IP;
1366 // If the original WaterList entry was "new water" on this iteration,
1367 // propagate that to the new island. This is just keeping NewWaterList
1368 // updated to match the WaterList, which will be updated below.
1369 if (NewWaterList.erase(WaterBB))
1370 NewWaterList.insert(NewIsland);
1372 // The new CPE goes before the following block (NewMBB).
1373 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1377 // we first see if a longer form of the instrucion could have reached
1378 // the constant. in that case we won't bother to split
1379 if (!NoLoadRelaxation) {
1380 result = findLongFormInRangeCPEntry(U, UserOffset);
1381 if (result != 0) return true;
1383 DEBUG(dbgs() << "No water found\n");
1384 createNewWater(CPUserIndex, UserOffset, NewMBB);
1386 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1387 // called while handling branches so that the water will be seen on the
1388 // next iteration for constant pools, but in this context, we don't want
1389 // it. Check for this so it will be removed from the WaterList.
1390 // Also remove any entry from NewWaterList.
1391 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1392 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1393 if (IP != WaterList.end())
1394 NewWaterList.erase(WaterBB);
1396 // We are adding new water. Update NewWaterList.
1397 NewWaterList.insert(NewIsland);
1400 // Remove the original WaterList entry; we want subsequent insertions in
1401 // this vicinity to go after the one we're about to insert. This
1402 // considerably reduces the number of times we have to move the same CPE
1403 // more than once and is also important to ensure the algorithm terminates.
1404 if (IP != WaterList.end())
1405 WaterList.erase(IP);
1407 // Okay, we know we can put an island before NewMBB now, do it!
1408 MF->insert(NewMBB, NewIsland);
1410 // Update internal data structures to account for the newly inserted MBB.
1411 updateForInsertedWaterBlock(NewIsland);
1413 // Decrement the old entry, and remove it if refcount becomes 0.
1414 decrementCPEReferenceCount(CPI, CPEMI);
1416 // No existing clone of this CPE is within range.
1417 // We will be generating a new clone. Get a UID for it.
1418 unsigned ID = createPICLabelUId();
1420 // Now that we have an island to add the CPE to, clone the original CPE and
1421 // add it to the island.
1422 U.HighWaterMark = NewIsland;
1423 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1424 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1425 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1428 // Mark the basic block as aligned as required by the const-pool entry.
1429 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1431 // Increase the size of the island block to account for the new entry.
1432 BBInfo[NewIsland->getNumber()].Size += Size;
1433 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1437 // Finally, change the CPI in the instruction operand to be ID.
1438 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1439 if (UserMI->getOperand(i).isCPI()) {
1440 UserMI->getOperand(i).setIndex(ID);
1444 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1445 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1450 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1451 /// sizes and offsets of impacted basic blocks.
1452 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1453 MachineBasicBlock *CPEBB = CPEMI->getParent();
1454 unsigned Size = CPEMI->getOperand(2).getImm();
1455 CPEMI->eraseFromParent();
1456 BBInfo[CPEBB->getNumber()].Size -= Size;
1457 // All succeeding offsets have the current size value added in, fix this.
1458 if (CPEBB->empty()) {
1459 BBInfo[CPEBB->getNumber()].Size = 0;
1461 // This block no longer needs to be aligned.
1462 CPEBB->setAlignment(0);
1464 // Entries are sorted by descending alignment, so realign from the front.
1465 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1467 adjustBBOffsetsAfter(CPEBB);
1468 // An island has only one predecessor BB and one successor BB. Check if
1469 // this BB's predecessor jumps directly to this BB's successor. This
1470 // shouldn't happen currently.
1471 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1472 // FIXME: remove the empty blocks after all the work is done?
1475 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1477 bool MipsConstantIslands::removeUnusedCPEntries() {
1478 unsigned MadeChange = false;
1479 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1480 std::vector<CPEntry> &CPEs = CPEntries[i];
1481 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1482 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1483 removeDeadCPEMI(CPEs[j].CPEMI);
1484 CPEs[j].CPEMI = NULL;
1492 /// isBBInRange - Returns true if the distance between specific MI and
1493 /// specific BB can fit in MI's displacement field.
1494 bool MipsConstantIslands::isBBInRange
1495 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1499 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1500 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1502 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1503 << " from BB#" << MI->getParent()->getNumber()
1504 << " max delta=" << MaxDisp
1505 << " from " << getOffsetOf(MI) << " to " << DestOffset
1506 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1508 if (BrOffset <= DestOffset) {
1509 // Branch before the Dest.
1510 if (DestOffset-BrOffset <= MaxDisp)
1513 if (BrOffset-DestOffset <= MaxDisp)
1519 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1520 /// away to fit in its displacement field.
1521 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1522 MachineInstr *MI = Br.MI;
1523 unsigned TargetOperand = branchTargetOperand(MI);
1524 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1526 // Check to see if the DestBB is already in-range.
1527 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1531 return fixupUnconditionalBr(Br);
1532 return fixupConditionalBr(Br);
1535 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1536 /// too far away to fit in its displacement field. If the LR register has been
1537 /// spilled in the epilogue, then we can use BL to implement a far jump.
1538 /// Otherwise, add an intermediate branch instruction to a branch.
1540 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1541 MachineInstr *MI = Br.MI;
1542 MachineBasicBlock *MBB = MI->getParent();
1543 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1544 // Use BL to implement far jump.
1545 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1546 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1547 Br.MaxDisp = BimmX16MaxDisp;
1548 MI->setDesc(TII->get(Mips::BimmX16));
1551 // need to give the math a more careful look here
1552 // this is really a segment address and not
1553 // a PC relative address. FIXME. But I think that
1554 // just reducing the bits by 1 as I've done is correct.
1555 // The basic block we are branching too much be longword aligned.
1556 // we know that RA is saved because we always save it right now.
1557 // this requirement will be relaxed later but we also have an alternate
1558 // way to implement this that I will implement that does not need jal.
1559 // We should have a way to back out this alignment restriction if we "can" later.
1560 // but it is not harmful.
1562 DestBB->setAlignment(2);
1563 Br.MaxDisp = ((1<<24)-1) * 2;
1564 MI->setDesc(TII->get(Mips::Jal16));
1566 BBInfo[MBB->getNumber()].Size += 2;
1567 adjustBBOffsetsAfter(MBB);
1571 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1577 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1578 /// far away to fit in its displacement field. It is converted to an inverse
1579 /// conditional branch + an unconditional branch to the destination.
1581 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1582 MachineInstr *MI = Br.MI;
1583 unsigned TargetOperand = branchTargetOperand(MI);
1584 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1585 unsigned Opcode = MI->getOpcode();
1586 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1587 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1589 // Check to see if the DestBB is already in-range.
1590 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1591 Br.MaxDisp = LongFormMaxOff;
1592 MI->setDesc(TII->get(LongFormOpcode));
1595 llvm_unreachable("Fixup of very long conditional branch not working yet.");
1597 // Add an unconditional branch to the destination and invert the branch
1598 // condition to jump over it:
1604 unsigned CCReg = 0; // FIXME
1605 unsigned CC=0; //FIXME
1607 // If the branch is at the end of its MBB and that has a fall-through block,
1608 // direct the updated conditional branch to the fall-through block. Otherwise,
1609 // split the MBB before the next instruction.
1610 MachineBasicBlock *MBB = MI->getParent();
1611 MachineInstr *BMI = &MBB->back();
1612 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1616 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1617 BMI->getOpcode() == Br.UncondBr) {
1618 // Last MI in the BB is an unconditional branch. Can we simply invert the
1619 // condition and swap destinations:
1625 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1626 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1627 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1629 BMI->getOperand(0).setMBB(DestBB);
1630 MI->getOperand(0).setMBB(NewDest);
1637 splitBlockBeforeInstr(MI);
1638 // No need for the branch to the next block. We're adding an unconditional
1639 // branch to the destination.
1640 int delta = TII->GetInstSizeInBytes(&MBB->back());
1641 BBInfo[MBB->getNumber()].Size -= delta;
1642 MBB->back().eraseFromParent();
1643 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1645 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1647 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1648 << " also invert condition and change dest. to BB#"
1649 << NextBB->getNumber() << "\n");
1651 // Insert a new conditional branch and a new unconditional branch.
1652 // Also update the ImmBranch as well as adding a new entry for the new branch.
1653 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1654 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1655 Br.MI = &MBB->back();
1656 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1657 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1658 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1659 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1660 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1662 // Remove the old conditional branch. It may or may not still be in MBB.
1663 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1664 MI->eraseFromParent();
1665 adjustBBOffsetsAfter(MBB);
1670 void MipsConstantIslands::prescanForConstants() {
1673 for (MachineFunction::iterator B =
1674 MF->begin(), E = MF->end(); B != E; ++B) {
1675 for (MachineBasicBlock::instr_iterator I =
1676 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1677 switch(I->getDesc().getOpcode()) {
1678 case Mips::LwConstant32: {
1679 PrescannedForConstants = true;
1680 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1681 J = I->getNumOperands();
1682 DEBUG(dbgs() << "num operands " << J << "\n");
1683 MachineOperand& Literal = I->getOperand(1);
1684 if (Literal.isImm()) {
1685 int64_t V = Literal.getImm();
1686 DEBUG(dbgs() << "literal " << V << "\n");
1688 Type::getInt32Ty(MF->getFunction()->getContext());
1689 const Constant *C = ConstantInt::get(Int32Ty, V);
1690 unsigned index = MCP->getConstantPoolIndex(C, 4);
1691 I->getOperand(2).ChangeToImmediate(index);
1692 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1693 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1694 I->RemoveOperand(1);
1695 I->RemoveOperand(1);
1696 I->addOperand(MachineOperand::CreateCPI(index, 0));
1697 I->addOperand(MachineOperand::CreateImm(4));