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 "MipsMachineFunction.h"
29 #include "MipsTargetMachine.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/InstIterator.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"
44 #include "llvm/Support/Format.h"
49 STATISTIC(NumCPEs, "Number of constpool entries");
50 STATISTIC(NumSplit, "Number of uncond branches inserted");
51 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
52 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
54 // FIXME: This option should be removed once it has received sufficient testing.
56 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
57 cl::desc("Align constant islands in code"));
60 // Rather than do make check tests with huge amounts of code, we force
61 // the test to use this amount.
63 static cl::opt<int> ConstantIslandsSmallOffset(
64 "mips-constant-islands-small-offset",
66 cl::desc("Make small offsets be this amount for testing purposes"),
70 // For testing purposes we tell it to not use relaxed load forms so that it
73 static cl::opt<bool> NoLoadRelaxation(
74 "mips-constant-islands-no-load-relaxation",
76 cl::desc("Don't relax loads to long loads - for testing purposes"),
83 typedef MachineBasicBlock::iterator Iter;
84 typedef MachineBasicBlock::reverse_iterator ReverseIter;
86 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
87 /// requires constant pool entries to be scattered among the instructions
88 /// inside a function. To do this, it completely ignores the normal LLVM
89 /// constant pool; instead, it places constants wherever it feels like with
90 /// special instructions.
92 /// The terminology used in this pass includes:
93 /// Islands - Clumps of constants placed in the function.
94 /// Water - Potential places where an island could be formed.
95 /// CPE - A constant pool entry that has been placed somewhere, which
96 /// tracks a list of users.
98 class MipsConstantIslands : public MachineFunctionPass {
100 /// BasicBlockInfo - Information about the offset and size of a single
102 struct BasicBlockInfo {
103 /// Offset - Distance from the beginning of the function to the beginning
104 /// of this basic block.
106 /// Offsets are computed assuming worst case padding before an aligned
107 /// block. This means that subtracting basic block offsets always gives a
108 /// conservative estimate of the real distance which may be smaller.
110 /// Because worst case padding is used, the computed offset of an aligned
111 /// block may not actually be aligned.
114 /// Size - Size of the basic block in bytes. If the block contains
115 /// inline assembly, this is a worst case estimate.
117 /// The size does not include any alignment padding whether from the
118 /// beginning of the block, or from an aligned jump table at the end.
121 // FIXME: ignore LogAlign for this patch
123 unsigned postOffset(unsigned LogAlign = 0) const {
124 unsigned PO = Offset + Size;
128 BasicBlockInfo() : Offset(0), Size(0) {}
132 std::vector<BasicBlockInfo> BBInfo;
134 /// WaterList - A sorted list of basic blocks where islands could be placed
135 /// (i.e. blocks that don't fall through to the following block, due
136 /// to a return, unreachable, or unconditional branch).
137 std::vector<MachineBasicBlock*> WaterList;
139 /// NewWaterList - The subset of WaterList that was created since the
140 /// previous iteration by inserting unconditional branches.
141 SmallSet<MachineBasicBlock*, 4> NewWaterList;
143 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
145 /// CPUser - One user of a constant pool, keeping the machine instruction
146 /// pointer, the constant pool being referenced, and the max displacement
147 /// allowed from the instruction to the CP. The HighWaterMark records the
148 /// highest basic block where a new CPEntry can be placed. To ensure this
149 /// pass terminates, the CP entries are initially placed at the end of the
150 /// function and then move monotonically to lower addresses. The
151 /// exception to this rule is when the current CP entry for a particular
152 /// CPUser is out of range, but there is another CP entry for the same
153 /// constant value in range. We want to use the existing in-range CP
154 /// entry, but if it later moves out of range, the search for new water
155 /// should resume where it left off. The HighWaterMark is used to record
160 MachineBasicBlock *HighWaterMark;
163 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
164 // with different displacements
165 unsigned LongFormOpcode;
168 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
170 unsigned longformmaxdisp, unsigned longformopcode)
171 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
172 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
174 HighWaterMark = CPEMI->getParent();
176 /// getMaxDisp - Returns the maximum displacement supported by MI.
177 unsigned getMaxDisp() const {
178 unsigned xMaxDisp = ConstantIslandsSmallOffset?
179 ConstantIslandsSmallOffset: MaxDisp;
182 void setMaxDisp(unsigned val) {
185 unsigned getLongFormMaxDisp() const {
186 return LongFormMaxDisp;
188 unsigned getLongFormOpcode() const {
189 return LongFormOpcode;
193 /// CPUsers - Keep track of all of the machine instructions that use various
194 /// constant pools and their max displacement.
195 std::vector<CPUser> CPUsers;
197 /// CPEntry - One per constant pool entry, keeping the machine instruction
198 /// pointer, the constpool index, and the number of CPUser's which
199 /// reference this entry.
204 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
205 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
208 /// CPEntries - Keep track of all of the constant pool entry machine
209 /// instructions. For each original constpool index (i.e. those that
210 /// existed upon entry to this pass), it keeps a vector of entries.
211 /// Original elements are cloned as we go along; the clones are
212 /// put in the vector of the original element, but have distinct CPIs.
213 std::vector<std::vector<CPEntry> > CPEntries;
215 /// ImmBranch - One per immediate branch, keeping the machine instruction
216 /// pointer, conditional or unconditional, the max displacement,
217 /// and (if isCond is true) the corresponding unconditional branch
221 unsigned MaxDisp : 31;
224 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
225 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
228 /// ImmBranches - Keep track of all the immediate branch instructions.
230 std::vector<ImmBranch> ImmBranches;
232 /// HasFarJump - True if any far jump instruction has been emitted during
233 /// the branch fix up pass.
236 const TargetMachine &TM;
239 const MipsSubtarget *STI;
240 const MipsInstrInfo *TII;
241 MipsFunctionInfo *MFI;
243 MachineConstantPool *MCP;
245 unsigned PICLabelUId;
246 bool PrescannedForConstants;
248 void initPICLabelUId(unsigned UId) {
253 unsigned createPICLabelUId() {
254 return PICLabelUId++;
259 MipsConstantIslands(TargetMachine &tm)
260 : MachineFunctionPass(ID), TM(tm),
261 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
262 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
263 STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
264 PrescannedForConstants(false){}
266 virtual const char *getPassName() const {
267 return "Mips Constant Islands";
270 bool runOnMachineFunction(MachineFunction &F);
272 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
273 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
274 unsigned getCPELogAlign(const MachineInstr *CPEMI);
275 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
276 unsigned getOffsetOf(MachineInstr *MI) const;
277 unsigned getUserOffset(CPUser&) const;
281 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
282 unsigned Disp, bool NegativeOK);
283 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
286 bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
289 void computeBlockSize(MachineBasicBlock *MBB);
290 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
291 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
292 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
293 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
294 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
295 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
296 bool findAvailableWater(CPUser&U, unsigned UserOffset,
297 water_iterator &WaterIter);
298 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
299 MachineBasicBlock *&NewMBB);
300 bool handleConstantPoolUser(unsigned CPUserIndex);
301 void removeDeadCPEMI(MachineInstr *CPEMI);
302 bool removeUnusedCPEntries();
303 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
304 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
305 bool DoDump = false);
306 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
307 CPUser &U, unsigned &Growth);
308 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
309 bool fixupImmediateBr(ImmBranch &Br);
310 bool fixupConditionalBr(ImmBranch &Br);
311 bool fixupUnconditionalBr(ImmBranch &Br);
313 void prescanForConstants();
319 char MipsConstantIslands::ID = 0;
320 } // end of anonymous namespace
323 bool MipsConstantIslands::isLongFormOffsetInRange
324 (unsigned UserOffset, unsigned TrialOffset,
326 return isOffsetInRange(UserOffset, TrialOffset,
327 U.getLongFormMaxDisp(), U.NegOk);
330 bool MipsConstantIslands::isOffsetInRange
331 (unsigned UserOffset, unsigned TrialOffset,
333 return isOffsetInRange(UserOffset, TrialOffset,
334 U.getMaxDisp(), U.NegOk);
336 /// print block size and offset information - debugging
337 void MipsConstantIslands::dumpBBs() {
339 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
340 const BasicBlockInfo &BBI = BBInfo[J];
341 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
342 << format(" size=%#x\n", BBInfo[J].Size);
346 /// createMipsLongBranchPass - Returns a pass that converts branches to long
348 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
349 return new MipsConstantIslands(tm);
352 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
353 // The intention is for this to be a mips16 only pass for now
356 MCP = mf.getConstantPool();
357 DEBUG(dbgs() << "constant island machine function " << "\n");
358 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
359 !MipsSubtarget::useConstantIslands()) {
362 TII = (const MipsInstrInfo*)MF->getTarget().getInstrInfo();
363 MFI = MF->getInfo<MipsFunctionInfo>();
364 DEBUG(dbgs() << "constant island processing " << "\n");
366 // will need to make predermination if there is any constants we need to
367 // put in constant islands. TBD.
369 if (!PrescannedForConstants) prescanForConstants();
372 // This pass invalidates liveness information when it splits basic blocks.
373 MF->getRegInfo().invalidateLiveness();
375 // Renumber all of the machine basic blocks in the function, guaranteeing that
376 // the numbers agree with the position of the block in the function.
377 MF->RenumberBlocks();
379 bool MadeChange = false;
381 // Perform the initial placement of the constant pool entries. To start with,
382 // we put them all at the end of the function.
383 std::vector<MachineInstr*> CPEMIs;
385 doInitialPlacement(CPEMIs);
387 /// The next UID to take is the first unused one.
388 initPICLabelUId(CPEMIs.size());
390 // Do the initial scan of the function, building up information about the
391 // sizes of each block, the location of all the water, and finding all of the
392 // constant pool users.
393 initializeFunctionInfo(CPEMIs);
397 /// Remove dead constant pool entries.
398 MadeChange |= removeUnusedCPEntries();
400 // Iteratively place constant pool entries and fix up branches until there
402 unsigned NoCPIters = 0, NoBRIters = 0;
405 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
406 bool CPChange = false;
407 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
408 CPChange |= handleConstantPoolUser(i);
409 if (CPChange && ++NoCPIters > 30)
410 report_fatal_error("Constant Island pass failed to converge!");
413 // Clear NewWaterList now. If we split a block for branches, it should
414 // appear as "new water" for the next iteration of constant pool placement.
415 NewWaterList.clear();
417 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
418 bool BRChange = false;
420 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
421 BRChange |= fixupImmediateBr(ImmBranches[i]);
422 if (BRChange && ++NoBRIters > 30)
423 report_fatal_error("Branch Fix Up pass failed to converge!");
426 if (!CPChange && !BRChange)
431 DEBUG(dbgs() << '\n'; dumpBBs());
441 /// doInitialPlacement - Perform the initial placement of the constant pool
442 /// entries. To start with, we put them all at the end of the function.
444 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
445 // Create the basic block to hold the CPE's.
446 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
450 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
451 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
453 // Mark the basic block as required by the const-pool.
454 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
455 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
457 // The function needs to be as aligned as the basic blocks. The linker may
458 // move functions around based on their alignment.
459 MF->ensureAlignment(BB->getAlignment());
461 // Order the entries in BB by descending alignment. That ensures correct
462 // alignment of all entries as long as BB is sufficiently aligned. Keep
463 // track of the insertion point for each alignment. We are going to bucket
464 // sort the entries as they are created.
465 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
467 // Add all of the constants from the constant pool to the end block, use an
468 // identity mapping of CPI's to CPE's.
469 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
471 const DataLayout &TD = *MF->getTarget().getDataLayout();
472 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
473 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
474 assert(Size >= 4 && "Too small constant pool entry");
475 unsigned Align = CPs[i].getAlignment();
476 assert(isPowerOf2_32(Align) && "Invalid alignment");
477 // Verify that all constant pool entries are a multiple of their alignment.
478 // If not, we would have to pad them out so that instructions stay aligned.
479 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
481 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
482 unsigned LogAlign = Log2_32(Align);
483 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
485 MachineInstr *CPEMI =
486 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
487 .addImm(i).addConstantPoolIndex(i).addImm(Size);
489 CPEMIs.push_back(CPEMI);
491 // Ensure that future entries with higher alignment get inserted before
492 // CPEMI. This is bucket sort with iterators.
493 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
494 if (InsPoint[a] == InsAt)
496 // Add a new CPEntry, but no corresponding CPUser yet.
497 std::vector<CPEntry> CPEs;
498 CPEs.push_back(CPEntry(CPEMI, i));
499 CPEntries.push_back(CPEs);
501 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
502 << Size << ", align = " << Align <<'\n');
507 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
508 /// into the block immediately after it.
509 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
510 // Get the next machine basic block in the function.
511 MachineFunction::iterator MBBI = MBB;
512 // Can't fall off end of function.
513 if (llvm::next(MBBI) == MBB->getParent()->end())
516 MachineBasicBlock *NextBB = llvm::next(MBBI);
517 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
518 E = MBB->succ_end(); I != E; ++I)
525 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
526 /// look up the corresponding CPEntry.
527 MipsConstantIslands::CPEntry
528 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
529 const MachineInstr *CPEMI) {
530 std::vector<CPEntry> &CPEs = CPEntries[CPI];
531 // Number of entries per constpool index should be small, just do a
533 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
534 if (CPEs[i].CPEMI == CPEMI)
540 /// getCPELogAlign - Returns the required alignment of the constant pool entry
541 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
542 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
543 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
545 // Everything is 4-byte aligned unless AlignConstantIslands is set.
546 if (!AlignConstantIslands)
549 unsigned CPI = CPEMI->getOperand(1).getIndex();
550 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
551 unsigned Align = MCP->getConstants()[CPI].getAlignment();
552 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
553 return Log2_32(Align);
556 /// initializeFunctionInfo - Do the initial scan of the function, building up
557 /// information about the sizes of each block, the location of all the water,
558 /// and finding all of the constant pool users.
559 void MipsConstantIslands::
560 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
562 BBInfo.resize(MF->getNumBlockIDs());
564 // First thing, compute the size of all basic blocks, and see if the function
565 // has any inline assembly in it. If so, we have to be conservative about
566 // alignment assumptions, as we don't know for sure the size of any
567 // instructions in the inline assembly.
568 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
572 // Compute block offsets.
573 adjustBBOffsetsAfter(MF->begin());
575 // Now go back through the instructions and build up our data structures.
576 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
578 MachineBasicBlock &MBB = *MBBI;
580 // If this block doesn't fall through into the next MBB, then this is
581 // 'water' that a constant pool island could be placed.
582 if (!BBHasFallthrough(&MBB))
583 WaterList.push_back(&MBB);
584 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
586 if (I->isDebugValue())
589 int Opc = I->getOpcode();
598 continue; // Ignore other JT branches
600 // Record this immediate branch.
601 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
602 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
606 if (Opc == Mips::CONSTPOOL_ENTRY)
610 // Scan the instructions for constant pool operands.
611 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
612 if (I->getOperand(op).isCPI()) {
614 // We found one. The addressing mode tells us the max displacement
615 // from the PC that this instruction permits.
617 // Basic size info comes from the TSFlags field.
621 unsigned LongFormBits = 0;
622 unsigned LongFormScale = 0;
623 unsigned LongFormOpcode = 0;
626 llvm_unreachable("Unknown addressing mode for CP reference!");
627 case Mips::LwRxPcTcp16:
630 LongFormOpcode = Mips::LwRxPcTcpX16;
634 case Mips::LwRxPcTcpX16:
640 // Remember that this is a user of a CP entry.
641 unsigned CPI = I->getOperand(op).getIndex();
642 MachineInstr *CPEMI = CPEMIs[CPI];
643 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
644 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
645 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
646 LongFormMaxOffs, LongFormOpcode));
648 // Increment corresponding CPEntry reference count.
649 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
650 assert(CPE && "Cannot find a corresponding CPEntry!");
653 // Instructions can only use one CP entry, don't bother scanning the
654 // rest of the operands.
664 /// computeBlockSize - Compute the size and some alignment information for MBB.
665 /// This function updates BBInfo directly.
666 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
667 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
670 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
672 BBI.Size += TII->GetInstSizeInBytes(I);
676 /// getOffsetOf - Return the current offset of the specified machine instruction
677 /// from the start of the function. This offset changes as stuff is moved
678 /// around inside the function.
679 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
680 MachineBasicBlock *MBB = MI->getParent();
682 // The offset is composed of two things: the sum of the sizes of all MBB's
683 // before this instruction's block, and the offset from the start of the block
685 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
687 // Sum instructions before MI in MBB.
688 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
689 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
690 Offset += TII->GetInstSizeInBytes(I);
695 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
697 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
698 const MachineBasicBlock *RHS) {
699 return LHS->getNumber() < RHS->getNumber();
702 /// updateForInsertedWaterBlock - When a block is newly inserted into the
703 /// machine function, it upsets all of the block numbers. Renumber the blocks
704 /// and update the arrays that parallel this numbering.
705 void MipsConstantIslands::updateForInsertedWaterBlock
706 (MachineBasicBlock *NewBB) {
707 // Renumber the MBB's to keep them consecutive.
708 NewBB->getParent()->RenumberBlocks(NewBB);
710 // Insert an entry into BBInfo to align it properly with the (newly
711 // renumbered) block numbers.
712 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
714 // Next, update WaterList. Specifically, we need to add NewMBB as having
715 // available water after it.
717 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
719 WaterList.insert(IP, NewBB);
722 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
723 return getOffsetOf(U.MI);
726 /// Split the basic block containing MI into two blocks, which are joined by
727 /// an unconditional branch. Update data structures and renumber blocks to
728 /// account for this change and returns the newly created block.
729 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
731 MachineBasicBlock *OrigBB = MI->getParent();
733 // Create a new MBB for the code after the OrigBB.
734 MachineBasicBlock *NewBB =
735 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
736 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
737 MF->insert(MBBI, NewBB);
739 // Splice the instructions starting with MI over to NewBB.
740 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
742 // Add an unconditional branch from OrigBB to NewBB.
743 // Note the new unconditional branch is not being recorded.
744 // There doesn't seem to be meaningful DebugInfo available; this doesn't
745 // correspond to anything in the source.
746 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
749 // Update the CFG. All succs of OrigBB are now succs of NewBB.
750 NewBB->transferSuccessors(OrigBB);
752 // OrigBB branches to NewBB.
753 OrigBB->addSuccessor(NewBB);
755 // Update internal data structures to account for the newly inserted MBB.
756 // This is almost the same as updateForInsertedWaterBlock, except that
757 // the Water goes after OrigBB, not NewBB.
758 MF->RenumberBlocks(NewBB);
760 // Insert an entry into BBInfo to align it properly with the (newly
761 // renumbered) block numbers.
762 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
764 // Next, update WaterList. Specifically, we need to add OrigMBB as having
765 // available water after it (but not if it's already there, which happens
766 // when splitting before a conditional branch that is followed by an
767 // unconditional branch - in that case we want to insert NewBB).
769 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
771 MachineBasicBlock* WaterBB = *IP;
772 if (WaterBB == OrigBB)
773 WaterList.insert(llvm::next(IP), NewBB);
775 WaterList.insert(IP, OrigBB);
776 NewWaterList.insert(OrigBB);
778 // Figure out how large the OrigBB is. As the first half of the original
779 // block, it cannot contain a tablejump. The size includes
780 // the new jump we added. (It should be possible to do this without
781 // recounting everything, but it's very confusing, and this is rarely
783 computeBlockSize(OrigBB);
785 // Figure out how large the NewMBB is. As the second half of the original
786 // block, it may contain a tablejump.
787 computeBlockSize(NewBB);
789 // All BBOffsets following these blocks must be modified.
790 adjustBBOffsetsAfter(OrigBB);
797 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
798 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
799 /// constant pool entry).
800 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
801 unsigned TrialOffset, unsigned MaxDisp,
803 if (UserOffset <= TrialOffset) {
804 // User before the Trial.
805 if (TrialOffset - UserOffset <= MaxDisp)
807 } else if (NegativeOK) {
808 if (UserOffset - TrialOffset <= MaxDisp)
814 /// isWaterInRange - Returns true if a CPE placed after the specified
815 /// Water (a basic block) will be in range for the specific MI.
817 /// Compute how much the function will grow by inserting a CPE after Water.
818 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
819 MachineBasicBlock* Water, CPUser &U,
821 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
822 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
823 unsigned NextBlockOffset, NextBlockAlignment;
824 MachineFunction::const_iterator NextBlock = Water;
825 if (++NextBlock == MF->end()) {
826 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
827 NextBlockAlignment = 0;
829 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
830 NextBlockAlignment = NextBlock->getAlignment();
832 unsigned Size = U.CPEMI->getOperand(2).getImm();
833 unsigned CPEEnd = CPEOffset + Size;
835 // The CPE may be able to hide in the alignment padding before the next
836 // block. It may also cause more padding to be required if it is more aligned
837 // that the next block.
838 if (CPEEnd > NextBlockOffset) {
839 Growth = CPEEnd - NextBlockOffset;
840 // Compute the padding that would go at the end of the CPE to align the next
842 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
844 // If the CPE is to be inserted before the instruction, that will raise
845 // the offset of the instruction. Also account for unknown alignment padding
846 // in blocks between CPE and the user.
847 if (CPEOffset < UserOffset)
848 UserOffset += Growth;
850 // CPE fits in existing padding.
853 return isOffsetInRange(UserOffset, CPEOffset, U);
856 /// isCPEntryInRange - Returns true if the distance between specific MI and
857 /// specific ConstPool entry instruction can fit in MI's displacement field.
858 bool MipsConstantIslands::isCPEntryInRange
859 (MachineInstr *MI, unsigned UserOffset,
860 MachineInstr *CPEMI, unsigned MaxDisp,
861 bool NegOk, bool DoDump) {
862 unsigned CPEOffset = getOffsetOf(CPEMI);
866 unsigned Block = MI->getParent()->getNumber();
867 const BasicBlockInfo &BBI = BBInfo[Block];
868 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
869 << " max delta=" << MaxDisp
870 << format(" insn address=%#x", UserOffset)
871 << " in BB#" << Block << ": "
872 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
873 << format("CPE address=%#x offset=%+d: ", CPEOffset,
874 int(CPEOffset-UserOffset));
878 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
882 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
883 /// unconditionally branches to its only successor.
884 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
885 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
887 MachineBasicBlock *Succ = *MBB->succ_begin();
888 MachineBasicBlock *Pred = *MBB->pred_begin();
889 MachineInstr *PredMI = &Pred->back();
890 if (PredMI->getOpcode() == Mips::Bimm16)
891 return PredMI->getOperand(0).getMBB() == Succ;
896 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
897 unsigned BBNum = BB->getNumber();
898 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
899 // Get the offset and known bits at the end of the layout predecessor.
900 // Include the alignment of the current block.
901 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
902 BBInfo[i].Offset = Offset;
906 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
907 /// and instruction CPEMI, and decrement its refcount. If the refcount
908 /// becomes 0 remove the entry and instruction. Returns true if we removed
909 /// the entry, false if we didn't.
911 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
912 MachineInstr *CPEMI) {
913 // Find the old entry. Eliminate it if it is no longer used.
914 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
915 assert(CPE && "Unexpected!");
916 if (--CPE->RefCount == 0) {
917 removeDeadCPEMI(CPEMI);
925 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
926 /// if not, see if an in-range clone of the CPE is in range, and if so,
927 /// change the data structures so the user references the clone. Returns:
928 /// 0 = no existing entry found
929 /// 1 = entry found, and there were no code insertions or deletions
930 /// 2 = entry found, and there were code insertions or deletions
931 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
933 MachineInstr *UserMI = U.MI;
934 MachineInstr *CPEMI = U.CPEMI;
936 // Check to see if the CPE is already in-range.
937 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
939 DEBUG(dbgs() << "In range\n");
943 // No. Look for previously created clones of the CPE that are in range.
944 unsigned CPI = CPEMI->getOperand(1).getIndex();
945 std::vector<CPEntry> &CPEs = CPEntries[CPI];
946 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
947 // We already tried this one
948 if (CPEs[i].CPEMI == CPEMI)
950 // Removing CPEs can leave empty entries, skip
951 if (CPEs[i].CPEMI == NULL)
953 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
955 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
956 << CPEs[i].CPI << "\n");
957 // Point the CPUser node to the replacement
958 U.CPEMI = CPEs[i].CPEMI;
959 // Change the CPI in the instruction operand to refer to the clone.
960 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
961 if (UserMI->getOperand(j).isCPI()) {
962 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
965 // Adjust the refcount of the clone...
967 // ...and the original. If we didn't remove the old entry, none of the
968 // addresses changed, so we don't need another pass.
969 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
975 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
976 /// This version checks if the longer form of the instruction can be used to
977 /// to satisfy things.
978 /// if not, see if an in-range clone of the CPE is in range, and if so,
979 /// change the data structures so the user references the clone. Returns:
980 /// 0 = no existing entry found
981 /// 1 = entry found, and there were no code insertions or deletions
982 /// 2 = entry found, and there were code insertions or deletions
983 int MipsConstantIslands::findLongFormInRangeCPEntry
984 (CPUser& U, unsigned UserOffset)
986 MachineInstr *UserMI = U.MI;
987 MachineInstr *CPEMI = U.CPEMI;
989 // Check to see if the CPE is already in-range.
990 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
991 U.getLongFormMaxDisp(), U.NegOk,
993 DEBUG(dbgs() << "In range\n");
994 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
995 U.setMaxDisp(U.getLongFormMaxDisp());
996 return 2; // instruction is longer length now
999 // No. Look for previously created clones of the CPE that are in range.
1000 unsigned CPI = CPEMI->getOperand(1).getIndex();
1001 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1002 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1003 // We already tried this one
1004 if (CPEs[i].CPEMI == CPEMI)
1006 // Removing CPEs can leave empty entries, skip
1007 if (CPEs[i].CPEMI == NULL)
1009 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1010 U.getLongFormMaxDisp(), U.NegOk)) {
1011 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1012 << CPEs[i].CPI << "\n");
1013 // Point the CPUser node to the replacement
1014 U.CPEMI = CPEs[i].CPEMI;
1015 // Change the CPI in the instruction operand to refer to the clone.
1016 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1017 if (UserMI->getOperand(j).isCPI()) {
1018 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1021 // Adjust the refcount of the clone...
1023 // ...and the original. If we didn't remove the old entry, none of the
1024 // addresses changed, so we don't need another pass.
1025 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1031 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1032 /// the specific unconditional branch instruction.
1033 static inline unsigned getUnconditionalBrDisp(int Opc) {
1036 return ((1<<10)-1)*2;
1038 return ((1<<16)-1)*2;
1042 return ((1<<16)-1)*2;
1045 /// findAvailableWater - Look for an existing entry in the WaterList in which
1046 /// we can place the CPE referenced from U so it's within range of U's MI.
1047 /// Returns true if found, false if not. If it returns true, WaterIter
1048 /// is set to the WaterList entry.
1049 /// To ensure that this pass
1050 /// terminates, the CPE location for a particular CPUser is only allowed to
1051 /// move to a lower address, so search backward from the end of the list and
1052 /// prefer the first water that is in range.
1053 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1054 water_iterator &WaterIter) {
1055 if (WaterList.empty())
1058 unsigned BestGrowth = ~0u;
1059 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1061 MachineBasicBlock* WaterBB = *IP;
1062 // Check if water is in range and is either at a lower address than the
1063 // current "high water mark" or a new water block that was created since
1064 // the previous iteration by inserting an unconditional branch. In the
1065 // latter case, we want to allow resetting the high water mark back to
1066 // this new water since we haven't seen it before. Inserting branches
1067 // should be relatively uncommon and when it does happen, we want to be
1068 // sure to take advantage of it for all the CPEs near that block, so that
1069 // we don't insert more branches than necessary.
1071 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1072 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1073 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1074 // This is the least amount of required padding seen so far.
1075 BestGrowth = Growth;
1077 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1078 << " Growth=" << Growth << '\n');
1080 // Keep looking unless it is perfect.
1081 if (BestGrowth == 0)
1087 return BestGrowth != ~0u;
1090 /// createNewWater - No existing WaterList entry will work for
1091 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1092 /// block is used if in range, and the conditional branch munged so control
1093 /// flow is correct. Otherwise the block is split to create a hole with an
1094 /// unconditional branch around it. In either case NewMBB is set to a
1095 /// block following which the new island can be inserted (the WaterList
1096 /// is not adjusted).
1097 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1098 unsigned UserOffset,
1099 MachineBasicBlock *&NewMBB) {
1100 CPUser &U = CPUsers[CPUserIndex];
1101 MachineInstr *UserMI = U.MI;
1102 MachineInstr *CPEMI = U.CPEMI;
1103 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1104 MachineBasicBlock *UserMBB = UserMI->getParent();
1105 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1107 // If the block does not end in an unconditional branch already, and if the
1108 // end of the block is within range, make new water there.
1109 if (BBHasFallthrough(UserMBB)) {
1110 // Size of branch to insert.
1112 // Compute the offset where the CPE will begin.
1113 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1115 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1116 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1117 << format(", expected CPE offset %#x\n", CPEOffset));
1118 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1119 // Add an unconditional branch from UserMBB to fallthrough block. Record
1120 // it for branch lengthening; this new branch will not get out of range,
1121 // but if the preceding conditional branch is out of range, the targets
1122 // will be exchanged, and the altered branch may be out of range, so the
1123 // machinery has to know about it.
1124 int UncondBr = Mips::Bimm16;
1125 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1126 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1127 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1128 MaxDisp, false, UncondBr));
1129 BBInfo[UserMBB->getNumber()].Size += Delta;
1130 adjustBBOffsetsAfter(UserMBB);
1135 // What a big block. Find a place within the block to split it.
1137 // Try to split the block so it's fully aligned. Compute the latest split
1138 // point where we can add a 4-byte branch instruction, and then align to
1139 // LogAlign which is the largest possible alignment in the function.
1140 unsigned LogAlign = MF->getAlignment();
1141 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1142 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1143 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1146 // The 4 in the following is for the unconditional branch we'll be inserting
1147 // Alignment of the island is handled
1148 // inside isOffsetInRange.
1149 BaseInsertOffset -= 4;
1151 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1152 << " la=" << LogAlign << '\n');
1154 // This could point off the end of the block if we've already got constant
1155 // pool entries following this block; only the last one is in the water list.
1156 // Back past any possible branches (allow for a conditional and a maximally
1157 // long unconditional).
1158 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1159 BaseInsertOffset = UserBBI.postOffset() - 8;
1160 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1162 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1163 CPEMI->getOperand(2).getImm();
1164 MachineBasicBlock::iterator MI = UserMI;
1166 unsigned CPUIndex = CPUserIndex+1;
1167 unsigned NumCPUsers = CPUsers.size();
1168 //MachineInstr *LastIT = 0;
1169 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1170 Offset < BaseInsertOffset;
1171 Offset += TII->GetInstSizeInBytes(MI),
1172 MI = llvm::next(MI)) {
1173 assert(MI != UserMBB->end() && "Fell off end of block");
1174 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1175 CPUser &U = CPUsers[CPUIndex];
1176 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1177 // Shift intertion point by one unit of alignment so it is within reach.
1178 BaseInsertOffset -= 1u << LogAlign;
1179 EndInsertOffset -= 1u << LogAlign;
1181 // This is overly conservative, as we don't account for CPEMIs being
1182 // reused within the block, but it doesn't matter much. Also assume CPEs
1183 // are added in order with alignment padding. We may eventually be able
1184 // to pack the aligned CPEs better.
1185 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1191 NewMBB = splitBlockBeforeInstr(MI);
1194 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1195 /// is out-of-range. If so, pick up the constant pool value and move it some
1196 /// place in-range. Return true if we changed any addresses (thus must run
1197 /// another pass of branch lengthening), false otherwise.
1198 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1199 CPUser &U = CPUsers[CPUserIndex];
1200 MachineInstr *UserMI = U.MI;
1201 MachineInstr *CPEMI = U.CPEMI;
1202 unsigned CPI = CPEMI->getOperand(1).getIndex();
1203 unsigned Size = CPEMI->getOperand(2).getImm();
1204 // Compute this only once, it's expensive.
1205 unsigned UserOffset = getUserOffset(U);
1207 // See if the current entry is within range, or there is a clone of it
1209 int result = findInRangeCPEntry(U, UserOffset);
1210 if (result==1) return false;
1211 else if (result==2) return true;
1214 // Look for water where we can place this CPE.
1215 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1216 MachineBasicBlock *NewMBB;
1218 if (findAvailableWater(U, UserOffset, IP)) {
1219 DEBUG(dbgs() << "Found water in range\n");
1220 MachineBasicBlock *WaterBB = *IP;
1222 // If the original WaterList entry was "new water" on this iteration,
1223 // propagate that to the new island. This is just keeping NewWaterList
1224 // updated to match the WaterList, which will be updated below.
1225 if (NewWaterList.erase(WaterBB))
1226 NewWaterList.insert(NewIsland);
1228 // The new CPE goes before the following block (NewMBB).
1229 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1233 // we first see if a longer form of the instrucion could have reached
1234 // the constant. in that case we won't bother to split
1235 if (!NoLoadRelaxation) {
1236 result = findLongFormInRangeCPEntry(U, UserOffset);
1237 if (result != 0) return true;
1239 DEBUG(dbgs() << "No water found\n");
1240 createNewWater(CPUserIndex, UserOffset, NewMBB);
1242 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1243 // called while handling branches so that the water will be seen on the
1244 // next iteration for constant pools, but in this context, we don't want
1245 // it. Check for this so it will be removed from the WaterList.
1246 // Also remove any entry from NewWaterList.
1247 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1248 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1249 if (IP != WaterList.end())
1250 NewWaterList.erase(WaterBB);
1252 // We are adding new water. Update NewWaterList.
1253 NewWaterList.insert(NewIsland);
1256 // Remove the original WaterList entry; we want subsequent insertions in
1257 // this vicinity to go after the one we're about to insert. This
1258 // considerably reduces the number of times we have to move the same CPE
1259 // more than once and is also important to ensure the algorithm terminates.
1260 if (IP != WaterList.end())
1261 WaterList.erase(IP);
1263 // Okay, we know we can put an island before NewMBB now, do it!
1264 MF->insert(NewMBB, NewIsland);
1266 // Update internal data structures to account for the newly inserted MBB.
1267 updateForInsertedWaterBlock(NewIsland);
1269 // Decrement the old entry, and remove it if refcount becomes 0.
1270 decrementCPEReferenceCount(CPI, CPEMI);
1272 // Now that we have an island to add the CPE to, clone the original CPE and
1273 // add it to the island.
1274 U.HighWaterMark = NewIsland;
1275 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1276 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1277 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1280 // Mark the basic block as aligned as required by the const-pool entry.
1281 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1283 // Increase the size of the island block to account for the new entry.
1284 BBInfo[NewIsland->getNumber()].Size += Size;
1285 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1287 // No existing clone of this CPE is within range.
1288 // We will be generating a new clone. Get a UID for it.
1289 unsigned ID = createPICLabelUId();
1291 // Finally, change the CPI in the instruction operand to be ID.
1292 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1293 if (UserMI->getOperand(i).isCPI()) {
1294 UserMI->getOperand(i).setIndex(ID);
1298 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1299 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1304 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1305 /// sizes and offsets of impacted basic blocks.
1306 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1307 MachineBasicBlock *CPEBB = CPEMI->getParent();
1308 unsigned Size = CPEMI->getOperand(2).getImm();
1309 CPEMI->eraseFromParent();
1310 BBInfo[CPEBB->getNumber()].Size -= Size;
1311 // All succeeding offsets have the current size value added in, fix this.
1312 if (CPEBB->empty()) {
1313 BBInfo[CPEBB->getNumber()].Size = 0;
1315 // This block no longer needs to be aligned.
1316 CPEBB->setAlignment(0);
1318 // Entries are sorted by descending alignment, so realign from the front.
1319 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1321 adjustBBOffsetsAfter(CPEBB);
1322 // An island has only one predecessor BB and one successor BB. Check if
1323 // this BB's predecessor jumps directly to this BB's successor. This
1324 // shouldn't happen currently.
1325 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1326 // FIXME: remove the empty blocks after all the work is done?
1329 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1331 bool MipsConstantIslands::removeUnusedCPEntries() {
1332 unsigned MadeChange = false;
1333 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1334 std::vector<CPEntry> &CPEs = CPEntries[i];
1335 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1336 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1337 removeDeadCPEMI(CPEs[j].CPEMI);
1338 CPEs[j].CPEMI = NULL;
1346 /// isBBInRange - Returns true if the distance between specific MI and
1347 /// specific BB can fit in MI's displacement field.
1348 bool MipsConstantIslands::isBBInRange
1349 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1353 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1354 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1356 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1357 << " from BB#" << MI->getParent()->getNumber()
1358 << " max delta=" << MaxDisp
1359 << " from " << getOffsetOf(MI) << " to " << DestOffset
1360 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1362 if (BrOffset <= DestOffset) {
1363 // Branch before the Dest.
1364 if (DestOffset-BrOffset <= MaxDisp)
1367 if (BrOffset-DestOffset <= MaxDisp)
1373 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1374 /// away to fit in its displacement field.
1375 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1376 MachineInstr *MI = Br.MI;
1377 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1379 // Check to see if the DestBB is already in-range.
1380 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1384 return fixupUnconditionalBr(Br);
1385 return fixupConditionalBr(Br);
1388 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1389 /// too far away to fit in its displacement field. If the LR register has been
1390 /// spilled in the epilogue, then we can use BL to implement a far jump.
1391 /// Otherwise, add an intermediate branch instruction to a branch.
1393 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1394 MachineInstr *MI = Br.MI;
1395 MachineBasicBlock *MBB = MI->getParent();
1396 // Use BL to implement far jump.
1397 Br.MaxDisp = ((1 << 16)-1) * 2;
1398 MI->setDesc(TII->get(Mips::BimmX16));
1399 BBInfo[MBB->getNumber()].Size += 2;
1400 adjustBBOffsetsAfter(MBB);
1404 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1409 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1410 /// far away to fit in its displacement field. It is converted to an inverse
1411 /// conditional branch + an unconditional branch to the destination.
1413 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1414 MachineInstr *MI = Br.MI;
1415 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1417 // Add an unconditional branch to the destination and invert the branch
1418 // condition to jump over it:
1424 unsigned CCReg = 0; // FIXME
1425 unsigned CC=0; //FIXME
1427 // If the branch is at the end of its MBB and that has a fall-through block,
1428 // direct the updated conditional branch to the fall-through block. Otherwise,
1429 // split the MBB before the next instruction.
1430 MachineBasicBlock *MBB = MI->getParent();
1431 MachineInstr *BMI = &MBB->back();
1432 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1436 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1437 BMI->getOpcode() == Br.UncondBr) {
1438 // Last MI in the BB is an unconditional branch. Can we simply invert the
1439 // condition and swap destinations:
1445 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1446 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1447 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1449 BMI->getOperand(0).setMBB(DestBB);
1450 MI->getOperand(0).setMBB(NewDest);
1457 splitBlockBeforeInstr(MI);
1458 // No need for the branch to the next block. We're adding an unconditional
1459 // branch to the destination.
1460 int delta = TII->GetInstSizeInBytes(&MBB->back());
1461 BBInfo[MBB->getNumber()].Size -= delta;
1462 MBB->back().eraseFromParent();
1463 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1465 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1467 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1468 << " also invert condition and change dest. to BB#"
1469 << NextBB->getNumber() << "\n");
1471 // Insert a new conditional branch and a new unconditional branch.
1472 // Also update the ImmBranch as well as adding a new entry for the new branch.
1473 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1474 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1475 Br.MI = &MBB->back();
1476 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1477 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1478 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1479 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1480 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1482 // Remove the old conditional branch. It may or may not still be in MBB.
1483 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1484 MI->eraseFromParent();
1485 adjustBBOffsetsAfter(MBB);
1490 void MipsConstantIslands::prescanForConstants() {
1493 PrescannedForConstants = true;
1494 for (MachineFunction::iterator B =
1495 MF->begin(), E = MF->end(); B != E; ++B) {
1496 for (MachineBasicBlock::instr_iterator I =
1497 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1498 switch(I->getDesc().getOpcode()) {
1499 case Mips::LwConstant32: {
1500 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1501 J = I->getNumOperands();
1502 DEBUG(dbgs() << "num operands " << J << "\n");
1503 MachineOperand& Literal = I->getOperand(1);
1504 if (Literal.isImm()) {
1505 int64_t V = Literal.getImm();
1506 DEBUG(dbgs() << "literal " << V << "\n");
1508 Type::getInt32Ty(MF->getFunction()->getContext());
1509 const Constant *C = ConstantInt::get(Int32Ty, V);
1510 unsigned index = MCP->getConstantPoolIndex(C, 4);
1511 I->getOperand(2).ChangeToImmediate(index);
1512 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1513 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1514 I->RemoveOperand(1);
1515 I->RemoveOperand(1);
1516 I->addOperand(MachineOperand::CreateCPI(index, 0));
1517 I->addOperand(MachineOperand::CreateImm(4));