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"),
69 /// UnknownPadding - Return the worst case padding that could result from
70 /// unknown offset bits. This does not include alignment padding caused by
71 /// known offset bits.
73 /// @param LogAlign log2(alignment)
74 /// @param KnownBits Number of known low offset bits.
75 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
76 if (KnownBits < LogAlign)
77 return (1u << LogAlign) - (1u << KnownBits);
84 typedef MachineBasicBlock::iterator Iter;
85 typedef MachineBasicBlock::reverse_iterator ReverseIter;
87 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
88 /// requires constant pool entries to be scattered among the instructions
89 /// inside a function. To do this, it completely ignores the normal LLVM
90 /// constant pool; instead, it places constants wherever it feels like with
91 /// special instructions.
93 /// The terminology used in this pass includes:
94 /// Islands - Clumps of constants placed in the function.
95 /// Water - Potential places where an island could be formed.
96 /// CPE - A constant pool entry that has been placed somewhere, which
97 /// tracks a list of users.
99 class MipsConstantIslands : public MachineFunctionPass {
101 /// BasicBlockInfo - Information about the offset and size of a single
103 struct BasicBlockInfo {
104 /// Offset - Distance from the beginning of the function to the beginning
105 /// of this basic block.
107 /// Offsets are computed assuming worst case padding before an aligned
108 /// block. This means that subtracting basic block offsets always gives a
109 /// conservative estimate of the real distance which may be smaller.
111 /// Because worst case padding is used, the computed offset of an aligned
112 /// block may not actually be aligned.
115 /// Size - Size of the basic block in bytes. If the block contains
116 /// inline assembly, this is a worst case estimate.
118 /// The size does not include any alignment padding whether from the
119 /// beginning of the block, or from an aligned jump table at the end.
122 /// KnownBits - The number of low bits in Offset that are known to be
123 /// exact. The remaining bits of Offset are an upper bound.
126 /// Unalign - When non-zero, the block contains instructions (inline asm)
127 /// of unknown size. The real size may be smaller than Size bytes by a
128 /// multiple of 1 << Unalign.
131 /// PostAlign - When non-zero, the block terminator contains a .align
132 /// directive, so the end of the block is aligned to 1 << PostAlign
136 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
139 /// Compute the number of known offset bits internally to this block.
140 /// This number should be used to predict worst case padding when
141 /// splitting the block.
142 unsigned internalKnownBits() const {
143 unsigned Bits = Unalign ? Unalign : KnownBits;
144 // If the block size isn't a multiple of the known bits, assume the
145 // worst case padding.
146 if (Size & ((1u << Bits) - 1))
147 Bits = countTrailingZeros(Size);
151 /// Compute the offset immediately following this block. If LogAlign is
152 /// specified, return the offset the successor block will get if it has
154 unsigned postOffset(unsigned LogAlign = 0) const {
155 unsigned PO = Offset + Size;
159 /// Compute the number of known low bits of postOffset. If this block
160 /// contains inline asm, the number of known bits drops to the
161 /// instruction alignment. An aligned terminator may increase the number
163 /// If LogAlign is given, also consider the alignment of the next block.
164 unsigned postKnownBits(unsigned LogAlign = 0) const {
165 return std::max(std::max(unsigned(PostAlign), LogAlign),
166 internalKnownBits());
170 std::vector<BasicBlockInfo> BBInfo;
172 /// WaterList - A sorted list of basic blocks where islands could be placed
173 /// (i.e. blocks that don't fall through to the following block, due
174 /// to a return, unreachable, or unconditional branch).
175 std::vector<MachineBasicBlock*> WaterList;
177 /// NewWaterList - The subset of WaterList that was created since the
178 /// previous iteration by inserting unconditional branches.
179 SmallSet<MachineBasicBlock*, 4> NewWaterList;
181 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
183 /// CPUser - One user of a constant pool, keeping the machine instruction
184 /// pointer, the constant pool being referenced, and the max displacement
185 /// allowed from the instruction to the CP. The HighWaterMark records the
186 /// highest basic block where a new CPEntry can be placed. To ensure this
187 /// pass terminates, the CP entries are initially placed at the end of the
188 /// function and then move monotonically to lower addresses. The
189 /// exception to this rule is when the current CP entry for a particular
190 /// CPUser is out of range, but there is another CP entry for the same
191 /// constant value in range. We want to use the existing in-range CP
192 /// entry, but if it later moves out of range, the search for new water
193 /// should resume where it left off. The HighWaterMark is used to record
198 MachineBasicBlock *HighWaterMark;
201 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
202 // with different displacements
203 unsigned LongFormOpcode;
208 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
209 bool neg, bool soimm,
210 unsigned longformmaxdisp, unsigned longformopcode)
211 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
212 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
213 NegOk(neg), IsSoImm(soimm), KnownAlignment(false) {
214 HighWaterMark = CPEMI->getParent();
216 /// getMaxDisp - Returns the maximum displacement supported by MI.
217 /// Correct for unknown alignment.
218 /// Conservatively subtract 2 bytes to handle weird alignment effects.
219 unsigned getMaxDisp() const {
220 unsigned xMaxDisp = ConstantIslandsSmallOffset?
221 ConstantIslandsSmallOffset: MaxDisp;
222 return (KnownAlignment ? xMaxDisp : xMaxDisp - 2) - 2;
224 unsigned getLongFormMaxDisp() const {
225 return (KnownAlignment ? LongFormMaxDisp : LongFormMaxDisp - 2) - 2;
227 unsigned getLongFormOpcode() const {
228 return LongFormOpcode;
232 /// CPUsers - Keep track of all of the machine instructions that use various
233 /// constant pools and their max displacement.
234 std::vector<CPUser> CPUsers;
236 /// CPEntry - One per constant pool entry, keeping the machine instruction
237 /// pointer, the constpool index, and the number of CPUser's which
238 /// reference this entry.
243 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
244 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
247 /// CPEntries - Keep track of all of the constant pool entry machine
248 /// instructions. For each original constpool index (i.e. those that
249 /// existed upon entry to this pass), it keeps a vector of entries.
250 /// Original elements are cloned as we go along; the clones are
251 /// put in the vector of the original element, but have distinct CPIs.
252 std::vector<std::vector<CPEntry> > CPEntries;
254 /// ImmBranch - One per immediate branch, keeping the machine instruction
255 /// pointer, conditional or unconditional, the max displacement,
256 /// and (if isCond is true) the corresponding unconditional branch
260 unsigned MaxDisp : 31;
263 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
264 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
267 /// ImmBranches - Keep track of all the immediate branch instructions.
269 std::vector<ImmBranch> ImmBranches;
271 /// HasFarJump - True if any far jump instruction has been emitted during
272 /// the branch fix up pass.
275 const TargetMachine &TM;
278 const MipsSubtarget *STI;
279 const MipsInstrInfo *TII;
280 MipsFunctionInfo *MFI;
282 MachineConstantPool *MCP;
284 unsigned PICLabelUId;
285 bool PrescannedForConstants;
287 void initPICLabelUId(unsigned UId) {
292 unsigned createPICLabelUId() {
293 return PICLabelUId++;
298 MipsConstantIslands(TargetMachine &tm)
299 : MachineFunctionPass(ID), TM(tm),
300 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
301 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
302 STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
303 PrescannedForConstants(false){}
305 virtual const char *getPassName() const {
306 return "Mips Constant Islands";
309 bool runOnMachineFunction(MachineFunction &F);
311 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
312 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
313 unsigned getCPELogAlign(const MachineInstr *CPEMI);
314 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
315 unsigned getOffsetOf(MachineInstr *MI) const;
316 unsigned getUserOffset(CPUser&) const;
320 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
321 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
322 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
325 bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
328 void computeBlockSize(MachineBasicBlock *MBB);
329 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
330 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
331 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
332 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
333 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
334 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
335 bool findAvailableWater(CPUser&U, unsigned UserOffset,
336 water_iterator &WaterIter);
337 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
338 MachineBasicBlock *&NewMBB);
339 bool handleConstantPoolUser(unsigned CPUserIndex);
340 void removeDeadCPEMI(MachineInstr *CPEMI);
341 bool removeUnusedCPEntries();
342 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
343 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
344 bool DoDump = false);
345 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
346 CPUser &U, unsigned &Growth);
347 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
348 bool fixupImmediateBr(ImmBranch &Br);
349 bool fixupConditionalBr(ImmBranch &Br);
350 bool fixupUnconditionalBr(ImmBranch &Br);
352 void prescanForConstants();
358 char MipsConstantIslands::ID = 0;
359 } // end of anonymous namespace
362 bool MipsConstantIslands::isLongFormOffsetInRange
363 (unsigned UserOffset, unsigned TrialOffset,
365 return isOffsetInRange(UserOffset, TrialOffset,
366 U.getLongFormMaxDisp(), U.NegOk, U.IsSoImm);
369 bool MipsConstantIslands::isOffsetInRange
370 (unsigned UserOffset, unsigned TrialOffset,
372 return isOffsetInRange(UserOffset, TrialOffset,
373 U.getMaxDisp(), U.NegOk, U.IsSoImm);
375 /// print block size and offset information - debugging
376 void MipsConstantIslands::dumpBBs() {
378 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
379 const BasicBlockInfo &BBI = BBInfo[J];
380 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
381 << " kb=" << unsigned(BBI.KnownBits)
382 << " ua=" << unsigned(BBI.Unalign)
383 << " pa=" << unsigned(BBI.PostAlign)
384 << format(" size=%#x\n", BBInfo[J].Size);
388 /// createMipsLongBranchPass - Returns a pass that converts branches to long
390 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
391 return new MipsConstantIslands(tm);
394 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
395 // The intention is for this to be a mips16 only pass for now
398 MCP = mf.getConstantPool();
399 DEBUG(dbgs() << "constant island machine function " << "\n");
400 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
401 !MipsSubtarget::useConstantIslands()) {
404 TII = (const MipsInstrInfo*)MF->getTarget().getInstrInfo();
405 MFI = MF->getInfo<MipsFunctionInfo>();
406 DEBUG(dbgs() << "constant island processing " << "\n");
408 // will need to make predermination if there is any constants we need to
409 // put in constant islands. TBD.
411 if (!PrescannedForConstants) prescanForConstants();
414 // This pass invalidates liveness information when it splits basic blocks.
415 MF->getRegInfo().invalidateLiveness();
417 // Renumber all of the machine basic blocks in the function, guaranteeing that
418 // the numbers agree with the position of the block in the function.
419 MF->RenumberBlocks();
421 bool MadeChange = false;
423 // Perform the initial placement of the constant pool entries. To start with,
424 // we put them all at the end of the function.
425 std::vector<MachineInstr*> CPEMIs;
427 doInitialPlacement(CPEMIs);
429 /// The next UID to take is the first unused one.
430 initPICLabelUId(CPEMIs.size());
432 // Do the initial scan of the function, building up information about the
433 // sizes of each block, the location of all the water, and finding all of the
434 // constant pool users.
435 initializeFunctionInfo(CPEMIs);
439 /// Remove dead constant pool entries.
440 MadeChange |= removeUnusedCPEntries();
442 // Iteratively place constant pool entries and fix up branches until there
444 unsigned NoCPIters = 0, NoBRIters = 0;
447 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
448 bool CPChange = false;
449 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
450 CPChange |= handleConstantPoolUser(i);
451 if (CPChange && ++NoCPIters > 30)
452 report_fatal_error("Constant Island pass failed to converge!");
455 // Clear NewWaterList now. If we split a block for branches, it should
456 // appear as "new water" for the next iteration of constant pool placement.
457 NewWaterList.clear();
459 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
460 bool BRChange = false;
462 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
463 BRChange |= fixupImmediateBr(ImmBranches[i]);
464 if (BRChange && ++NoBRIters > 30)
465 report_fatal_error("Branch Fix Up pass failed to converge!");
468 if (!CPChange && !BRChange)
473 DEBUG(dbgs() << '\n'; dumpBBs());
483 /// doInitialPlacement - Perform the initial placement of the constant pool
484 /// entries. To start with, we put them all at the end of the function.
486 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
487 // Create the basic block to hold the CPE's.
488 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
492 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
493 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
495 // Mark the basic block as required by the const-pool.
496 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
497 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
499 // The function needs to be as aligned as the basic blocks. The linker may
500 // move functions around based on their alignment.
501 MF->ensureAlignment(BB->getAlignment());
503 // Order the entries in BB by descending alignment. That ensures correct
504 // alignment of all entries as long as BB is sufficiently aligned. Keep
505 // track of the insertion point for each alignment. We are going to bucket
506 // sort the entries as they are created.
507 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
509 // Add all of the constants from the constant pool to the end block, use an
510 // identity mapping of CPI's to CPE's.
511 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
513 const DataLayout &TD = *MF->getTarget().getDataLayout();
514 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
515 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
516 assert(Size >= 4 && "Too small constant pool entry");
517 unsigned Align = CPs[i].getAlignment();
518 assert(isPowerOf2_32(Align) && "Invalid alignment");
519 // Verify that all constant pool entries are a multiple of their alignment.
520 // If not, we would have to pad them out so that instructions stay aligned.
521 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
523 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
524 unsigned LogAlign = Log2_32(Align);
525 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
527 MachineInstr *CPEMI =
528 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
529 .addImm(i).addConstantPoolIndex(i).addImm(Size);
531 CPEMIs.push_back(CPEMI);
533 // Ensure that future entries with higher alignment get inserted before
534 // CPEMI. This is bucket sort with iterators.
535 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
536 if (InsPoint[a] == InsAt)
538 // Add a new CPEntry, but no corresponding CPUser yet.
539 std::vector<CPEntry> CPEs;
540 CPEs.push_back(CPEntry(CPEMI, i));
541 CPEntries.push_back(CPEs);
543 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
544 << Size << ", align = " << Align <<'\n');
549 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
550 /// into the block immediately after it.
551 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
552 // Get the next machine basic block in the function.
553 MachineFunction::iterator MBBI = MBB;
554 // Can't fall off end of function.
555 if (llvm::next(MBBI) == MBB->getParent()->end())
558 MachineBasicBlock *NextBB = llvm::next(MBBI);
559 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
560 E = MBB->succ_end(); I != E; ++I)
567 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
568 /// look up the corresponding CPEntry.
569 MipsConstantIslands::CPEntry
570 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
571 const MachineInstr *CPEMI) {
572 std::vector<CPEntry> &CPEs = CPEntries[CPI];
573 // Number of entries per constpool index should be small, just do a
575 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
576 if (CPEs[i].CPEMI == CPEMI)
582 /// getCPELogAlign - Returns the required alignment of the constant pool entry
583 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
584 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
585 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
587 // Everything is 4-byte aligned unless AlignConstantIslands is set.
588 if (!AlignConstantIslands)
591 unsigned CPI = CPEMI->getOperand(1).getIndex();
592 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
593 unsigned Align = MCP->getConstants()[CPI].getAlignment();
594 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
595 return Log2_32(Align);
598 /// initializeFunctionInfo - Do the initial scan of the function, building up
599 /// information about the sizes of each block, the location of all the water,
600 /// and finding all of the constant pool users.
601 void MipsConstantIslands::
602 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
604 BBInfo.resize(MF->getNumBlockIDs());
606 // First thing, compute the size of all basic blocks, and see if the function
607 // has any inline assembly in it. If so, we have to be conservative about
608 // alignment assumptions, as we don't know for sure the size of any
609 // instructions in the inline assembly.
610 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
613 // The known bits of the entry block offset are determined by the function
615 BBInfo.front().KnownBits = MF->getAlignment();
617 // Compute block offsets.
618 adjustBBOffsetsAfter(MF->begin());
620 // Now go back through the instructions and build up our data structures.
621 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
623 MachineBasicBlock &MBB = *MBBI;
625 // If this block doesn't fall through into the next MBB, then this is
626 // 'water' that a constant pool island could be placed.
627 if (!BBHasFallthrough(&MBB))
628 WaterList.push_back(&MBB);
629 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
631 if (I->isDebugValue())
634 int Opc = I->getOpcode();
643 continue; // Ignore other JT branches
645 // Record this immediate branch.
646 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
647 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
652 if (Opc == Mips::CONSTPOOL_ENTRY)
656 // Scan the instructions for constant pool operands.
657 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
658 if (I->getOperand(op).isCPI()) {
660 // We found one. The addressing mode tells us the max displacement
661 // from the PC that this instruction permits.
663 // Basic size info comes from the TSFlags field.
667 bool IsSoImm = false;
668 unsigned LongFormBits = 0;
669 unsigned LongFormScale = 0;
670 unsigned LongFormOpcode = 0;
673 llvm_unreachable("Unknown addressing mode for CP reference!");
674 case Mips::LwRxPcTcp16:
677 LongFormOpcode = Mips::LwRxPcTcpX16;
679 case Mips::LwRxPcTcpX16:
684 // Remember that this is a user of a CP entry.
685 unsigned CPI = I->getOperand(op).getIndex();
686 MachineInstr *CPEMI = CPEMIs[CPI];
687 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
688 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
689 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
690 IsSoImm, LongFormMaxOffs,
693 // Increment corresponding CPEntry reference count.
694 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
695 assert(CPE && "Cannot find a corresponding CPEntry!");
698 // Instructions can only use one CP entry, don't bother scanning the
699 // rest of the operands.
709 /// computeBlockSize - Compute the size and some alignment information for MBB.
710 /// This function updates BBInfo directly.
711 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
712 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
717 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
719 BBI.Size += TII->GetInstSizeInBytes(I);
723 /// getOffsetOf - Return the current offset of the specified machine instruction
724 /// from the start of the function. This offset changes as stuff is moved
725 /// around inside the function.
726 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
727 MachineBasicBlock *MBB = MI->getParent();
729 // The offset is composed of two things: the sum of the sizes of all MBB's
730 // before this instruction's block, and the offset from the start of the block
732 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
734 // Sum instructions before MI in MBB.
735 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
736 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
737 Offset += TII->GetInstSizeInBytes(I);
742 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
744 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
745 const MachineBasicBlock *RHS) {
746 return LHS->getNumber() < RHS->getNumber();
749 /// updateForInsertedWaterBlock - When a block is newly inserted into the
750 /// machine function, it upsets all of the block numbers. Renumber the blocks
751 /// and update the arrays that parallel this numbering.
752 void MipsConstantIslands::updateForInsertedWaterBlock
753 (MachineBasicBlock *NewBB) {
754 // Renumber the MBB's to keep them consecutive.
755 NewBB->getParent()->RenumberBlocks(NewBB);
757 // Insert an entry into BBInfo to align it properly with the (newly
758 // renumbered) block numbers.
759 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
761 // Next, update WaterList. Specifically, we need to add NewMBB as having
762 // available water after it.
764 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
766 WaterList.insert(IP, NewBB);
769 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
770 return getOffsetOf(U.MI);
773 /// Split the basic block containing MI into two blocks, which are joined by
774 /// an unconditional branch. Update data structures and renumber blocks to
775 /// account for this change and returns the newly created block.
776 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
778 MachineBasicBlock *OrigBB = MI->getParent();
780 // Create a new MBB for the code after the OrigBB.
781 MachineBasicBlock *NewBB =
782 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
783 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
784 MF->insert(MBBI, NewBB);
786 // Splice the instructions starting with MI over to NewBB.
787 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
789 // Add an unconditional branch from OrigBB to NewBB.
790 // Note the new unconditional branch is not being recorded.
791 // There doesn't seem to be meaningful DebugInfo available; this doesn't
792 // correspond to anything in the source.
793 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::BimmX16)).addMBB(NewBB);
796 // Update the CFG. All succs of OrigBB are now succs of NewBB.
797 NewBB->transferSuccessors(OrigBB);
799 // OrigBB branches to NewBB.
800 OrigBB->addSuccessor(NewBB);
802 // Update internal data structures to account for the newly inserted MBB.
803 // This is almost the same as updateForInsertedWaterBlock, except that
804 // the Water goes after OrigBB, not NewBB.
805 MF->RenumberBlocks(NewBB);
807 // Insert an entry into BBInfo to align it properly with the (newly
808 // renumbered) block numbers.
809 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
811 // Next, update WaterList. Specifically, we need to add OrigMBB as having
812 // available water after it (but not if it's already there, which happens
813 // when splitting before a conditional branch that is followed by an
814 // unconditional branch - in that case we want to insert NewBB).
816 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
818 MachineBasicBlock* WaterBB = *IP;
819 if (WaterBB == OrigBB)
820 WaterList.insert(llvm::next(IP), NewBB);
822 WaterList.insert(IP, OrigBB);
823 NewWaterList.insert(OrigBB);
825 // Figure out how large the OrigBB is. As the first half of the original
826 // block, it cannot contain a tablejump. The size includes
827 // the new jump we added. (It should be possible to do this without
828 // recounting everything, but it's very confusing, and this is rarely
830 computeBlockSize(OrigBB);
832 // Figure out how large the NewMBB is. As the second half of the original
833 // block, it may contain a tablejump.
834 computeBlockSize(NewBB);
836 // All BBOffsets following these blocks must be modified.
837 adjustBBOffsetsAfter(OrigBB);
844 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
845 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
846 /// constant pool entry).
847 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
848 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
849 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
850 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
851 unsigned TrialOffset, unsigned MaxDisp,
852 bool NegativeOK, bool IsSoImm) {
853 if (UserOffset <= TrialOffset) {
854 // User before the Trial.
855 if (TrialOffset - UserOffset <= MaxDisp)
857 // FIXME: Make use full range of soimm values.
858 } else if (NegativeOK) {
859 if (UserOffset - TrialOffset <= MaxDisp)
861 // FIXME: Make use full range of soimm values.
866 /// isWaterInRange - Returns true if a CPE placed after the specified
867 /// Water (a basic block) will be in range for the specific MI.
869 /// Compute how much the function will grow by inserting a CPE after Water.
870 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
871 MachineBasicBlock* Water, CPUser &U,
873 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
874 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
875 unsigned NextBlockOffset, NextBlockAlignment;
876 MachineFunction::const_iterator NextBlock = Water;
877 if (++NextBlock == MF->end()) {
878 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
879 NextBlockAlignment = 0;
881 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
882 NextBlockAlignment = NextBlock->getAlignment();
884 unsigned Size = U.CPEMI->getOperand(2).getImm();
885 unsigned CPEEnd = CPEOffset + Size;
887 // The CPE may be able to hide in the alignment padding before the next
888 // block. It may also cause more padding to be required if it is more aligned
889 // that the next block.
890 if (CPEEnd > NextBlockOffset) {
891 Growth = CPEEnd - NextBlockOffset;
892 // Compute the padding that would go at the end of the CPE to align the next
894 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
896 // If the CPE is to be inserted before the instruction, that will raise
897 // the offset of the instruction. Also account for unknown alignment padding
898 // in blocks between CPE and the user.
899 if (CPEOffset < UserOffset)
900 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
902 // CPE fits in existing padding.
905 return isOffsetInRange(UserOffset, CPEOffset, U);
908 /// isCPEntryInRange - Returns true if the distance between specific MI and
909 /// specific ConstPool entry instruction can fit in MI's displacement field.
910 bool MipsConstantIslands::isCPEntryInRange
911 (MachineInstr *MI, unsigned UserOffset,
912 MachineInstr *CPEMI, unsigned MaxDisp,
913 bool NegOk, bool DoDump) {
914 unsigned CPEOffset = getOffsetOf(CPEMI);
918 unsigned Block = MI->getParent()->getNumber();
919 const BasicBlockInfo &BBI = BBInfo[Block];
920 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
921 << " max delta=" << MaxDisp
922 << format(" insn address=%#x", UserOffset)
923 << " in BB#" << Block << ": "
924 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
925 << format("CPE address=%#x offset=%+d: ", CPEOffset,
926 int(CPEOffset-UserOffset));
930 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
934 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
935 /// unconditionally branches to its only successor.
936 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
937 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
939 MachineBasicBlock *Succ = *MBB->succ_begin();
940 MachineBasicBlock *Pred = *MBB->pred_begin();
941 MachineInstr *PredMI = &Pred->back();
942 if (PredMI->getOpcode() == Mips::BimmX16)
943 return PredMI->getOperand(0).getMBB() == Succ;
948 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
949 unsigned BBNum = BB->getNumber();
950 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
951 // Get the offset and known bits at the end of the layout predecessor.
952 // Include the alignment of the current block.
953 unsigned Offset = BBInfo[i - 1].postOffset();
954 BBInfo[i].Offset = Offset;
958 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
959 /// and instruction CPEMI, and decrement its refcount. If the refcount
960 /// becomes 0 remove the entry and instruction. Returns true if we removed
961 /// the entry, false if we didn't.
963 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
964 MachineInstr *CPEMI) {
965 // Find the old entry. Eliminate it if it is no longer used.
966 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
967 assert(CPE && "Unexpected!");
968 if (--CPE->RefCount == 0) {
969 removeDeadCPEMI(CPEMI);
977 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
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::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
985 MachineInstr *UserMI = U.MI;
986 MachineInstr *CPEMI = U.CPEMI;
988 // Check to see if the CPE is already in-range.
989 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
991 DEBUG(dbgs() << "In range\n");
995 // No. Look for previously created clones of the CPE that are in range.
996 unsigned CPI = CPEMI->getOperand(1).getIndex();
997 std::vector<CPEntry> &CPEs = CPEntries[CPI];
998 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
999 // We already tried this one
1000 if (CPEs[i].CPEMI == CPEMI)
1002 // Removing CPEs can leave empty entries, skip
1003 if (CPEs[i].CPEMI == NULL)
1005 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1007 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1008 << CPEs[i].CPI << "\n");
1009 // Point the CPUser node to the replacement
1010 U.CPEMI = CPEs[i].CPEMI;
1011 // Change the CPI in the instruction operand to refer to the clone.
1012 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1013 if (UserMI->getOperand(j).isCPI()) {
1014 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1017 // Adjust the refcount of the clone...
1019 // ...and the original. If we didn't remove the old entry, none of the
1020 // addresses changed, so we don't need another pass.
1021 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1027 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1028 /// This version checks if the longer form of the instruction can be used to
1029 /// to satisfy things.
1030 /// if not, see if an in-range clone of the CPE is in range, and if so,
1031 /// change the data structures so the user references the clone. Returns:
1032 /// 0 = no existing entry found
1033 /// 1 = entry found, and there were no code insertions or deletions
1034 /// 2 = entry found, and there were code insertions or deletions
1035 int MipsConstantIslands::findLongFormInRangeCPEntry
1036 (CPUser& U, unsigned UserOffset)
1038 MachineInstr *UserMI = U.MI;
1039 MachineInstr *CPEMI = U.CPEMI;
1041 // Check to see if the CPE is already in-range.
1042 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1043 U.getLongFormMaxDisp(), U.NegOk,
1045 DEBUG(dbgs() << "In range\n");
1046 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1047 return 2; // instruction is longer length now
1050 // No. Look for previously created clones of the CPE that are in range.
1051 unsigned CPI = CPEMI->getOperand(1).getIndex();
1052 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1053 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1054 // We already tried this one
1055 if (CPEs[i].CPEMI == CPEMI)
1057 // Removing CPEs can leave empty entries, skip
1058 if (CPEs[i].CPEMI == NULL)
1060 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1061 U.getLongFormMaxDisp(), U.NegOk)) {
1062 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1063 << CPEs[i].CPI << "\n");
1064 // Point the CPUser node to the replacement
1065 U.CPEMI = CPEs[i].CPEMI;
1066 // Change the CPI in the instruction operand to refer to the clone.
1067 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1068 if (UserMI->getOperand(j).isCPI()) {
1069 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1072 // Adjust the refcount of the clone...
1074 // ...and the original. If we didn't remove the old entry, none of the
1075 // addresses changed, so we don't need another pass.
1076 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1082 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1083 /// the specific unconditional branch instruction.
1084 static inline unsigned getUnconditionalBrDisp(int Opc) {
1087 return ((1<<16)-1)*2;
1091 return ((1<<16)-1)*2;
1094 /// findAvailableWater - Look for an existing entry in the WaterList in which
1095 /// we can place the CPE referenced from U so it's within range of U's MI.
1096 /// Returns true if found, false if not. If it returns true, WaterIter
1097 /// is set to the WaterList entry.
1098 /// To ensure that this pass
1099 /// terminates, the CPE location for a particular CPUser is only allowed to
1100 /// move to a lower address, so search backward from the end of the list and
1101 /// prefer the first water that is in range.
1102 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1103 water_iterator &WaterIter) {
1104 if (WaterList.empty())
1107 unsigned BestGrowth = ~0u;
1108 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1110 MachineBasicBlock* WaterBB = *IP;
1111 // Check if water is in range and is either at a lower address than the
1112 // current "high water mark" or a new water block that was created since
1113 // the previous iteration by inserting an unconditional branch. In the
1114 // latter case, we want to allow resetting the high water mark back to
1115 // this new water since we haven't seen it before. Inserting branches
1116 // should be relatively uncommon and when it does happen, we want to be
1117 // sure to take advantage of it for all the CPEs near that block, so that
1118 // we don't insert more branches than necessary.
1120 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1121 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1122 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1123 // This is the least amount of required padding seen so far.
1124 BestGrowth = Growth;
1126 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1127 << " Growth=" << Growth << '\n');
1129 // Keep looking unless it is perfect.
1130 if (BestGrowth == 0)
1136 return BestGrowth != ~0u;
1139 /// createNewWater - No existing WaterList entry will work for
1140 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1141 /// block is used if in range, and the conditional branch munged so control
1142 /// flow is correct. Otherwise the block is split to create a hole with an
1143 /// unconditional branch around it. In either case NewMBB is set to a
1144 /// block following which the new island can be inserted (the WaterList
1145 /// is not adjusted).
1146 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1147 unsigned UserOffset,
1148 MachineBasicBlock *&NewMBB) {
1149 CPUser &U = CPUsers[CPUserIndex];
1150 MachineInstr *UserMI = U.MI;
1151 MachineInstr *CPEMI = U.CPEMI;
1152 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1153 MachineBasicBlock *UserMBB = UserMI->getParent();
1154 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1156 // If the block does not end in an unconditional branch already, and if the
1157 // end of the block is within range, make new water there.
1158 if (BBHasFallthrough(UserMBB)) {
1159 // Size of branch to insert.
1161 // Compute the offset where the CPE will begin.
1162 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1164 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1165 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1166 << format(", expected CPE offset %#x\n", CPEOffset));
1167 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1168 // Add an unconditional branch from UserMBB to fallthrough block. Record
1169 // it for branch lengthening; this new branch will not get out of range,
1170 // but if the preceding conditional branch is out of range, the targets
1171 // will be exchanged, and the altered branch may be out of range, so the
1172 // machinery has to know about it.
1173 int UncondBr = Mips::BimmX16;
1174 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1175 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1176 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1177 MaxDisp, false, UncondBr));
1178 BBInfo[UserMBB->getNumber()].Size += Delta;
1179 adjustBBOffsetsAfter(UserMBB);
1184 // What a big block. Find a place within the block to split it.
1186 // Try to split the block so it's fully aligned. Compute the latest split
1187 // point where we can add a 4-byte branch instruction, and then align to
1188 // LogAlign which is the largest possible alignment in the function.
1189 unsigned LogAlign = MF->getAlignment();
1190 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1191 unsigned KnownBits = UserBBI.internalKnownBits();
1192 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1193 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1194 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1197 // The 4 in the following is for the unconditional branch we'll be inserting
1198 // Alignment of the island is handled
1199 // inside isOffsetInRange.
1200 BaseInsertOffset -= 4;
1202 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1203 << " la=" << LogAlign
1204 << " kb=" << KnownBits
1205 << " up=" << UPad << '\n');
1207 // This could point off the end of the block if we've already got constant
1208 // pool entries following this block; only the last one is in the water list.
1209 // Back past any possible branches (allow for a conditional and a maximally
1210 // long unconditional).
1211 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1212 BaseInsertOffset = UserBBI.postOffset() - UPad - 8;
1213 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1215 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1216 CPEMI->getOperand(2).getImm();
1217 MachineBasicBlock::iterator MI = UserMI;
1219 unsigned CPUIndex = CPUserIndex+1;
1220 unsigned NumCPUsers = CPUsers.size();
1221 //MachineInstr *LastIT = 0;
1222 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1223 Offset < BaseInsertOffset;
1224 Offset += TII->GetInstSizeInBytes(MI),
1225 MI = llvm::next(MI)) {
1226 assert(MI != UserMBB->end() && "Fell off end of block");
1227 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1228 CPUser &U = CPUsers[CPUIndex];
1229 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1230 // Shift intertion point by one unit of alignment so it is within reach.
1231 BaseInsertOffset -= 1u << LogAlign;
1232 EndInsertOffset -= 1u << LogAlign;
1234 // This is overly conservative, as we don't account for CPEMIs being
1235 // reused within the block, but it doesn't matter much. Also assume CPEs
1236 // are added in order with alignment padding. We may eventually be able
1237 // to pack the aligned CPEs better.
1238 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1244 NewMBB = splitBlockBeforeInstr(MI);
1247 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1248 /// is out-of-range. If so, pick up the constant pool value and move it some
1249 /// place in-range. Return true if we changed any addresses (thus must run
1250 /// another pass of branch lengthening), false otherwise.
1251 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1252 CPUser &U = CPUsers[CPUserIndex];
1253 MachineInstr *UserMI = U.MI;
1254 MachineInstr *CPEMI = U.CPEMI;
1255 unsigned CPI = CPEMI->getOperand(1).getIndex();
1256 unsigned Size = CPEMI->getOperand(2).getImm();
1257 // Compute this only once, it's expensive.
1258 unsigned UserOffset = getUserOffset(U);
1260 // See if the current entry is within range, or there is a clone of it
1262 int result = findInRangeCPEntry(U, UserOffset);
1263 if (result==1) return false;
1264 else if (result==2) return true;
1267 // Look for water where we can place this CPE.
1268 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1269 MachineBasicBlock *NewMBB;
1271 if (findAvailableWater(U, UserOffset, IP)) {
1272 DEBUG(dbgs() << "Found water in range\n");
1273 MachineBasicBlock *WaterBB = *IP;
1275 // If the original WaterList entry was "new water" on this iteration,
1276 // propagate that to the new island. This is just keeping NewWaterList
1277 // updated to match the WaterList, which will be updated below.
1278 if (NewWaterList.erase(WaterBB))
1279 NewWaterList.insert(NewIsland);
1281 // The new CPE goes before the following block (NewMBB).
1282 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1286 // we first see if a longer form of the instrucion could have reached
1287 // the constant. in that case we won't bother to split
1289 result = findLongFormInRangeCPEntry(U, UserOffset);
1291 DEBUG(dbgs() << "No water found\n");
1292 createNewWater(CPUserIndex, UserOffset, NewMBB);
1294 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1295 // called while handling branches so that the water will be seen on the
1296 // next iteration for constant pools, but in this context, we don't want
1297 // it. Check for this so it will be removed from the WaterList.
1298 // Also remove any entry from NewWaterList.
1299 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1300 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1301 if (IP != WaterList.end())
1302 NewWaterList.erase(WaterBB);
1304 // We are adding new water. Update NewWaterList.
1305 NewWaterList.insert(NewIsland);
1308 // Remove the original WaterList entry; we want subsequent insertions in
1309 // this vicinity to go after the one we're about to insert. This
1310 // considerably reduces the number of times we have to move the same CPE
1311 // more than once and is also important to ensure the algorithm terminates.
1312 if (IP != WaterList.end())
1313 WaterList.erase(IP);
1315 // Okay, we know we can put an island before NewMBB now, do it!
1316 MF->insert(NewMBB, NewIsland);
1318 // Update internal data structures to account for the newly inserted MBB.
1319 updateForInsertedWaterBlock(NewIsland);
1321 // Decrement the old entry, and remove it if refcount becomes 0.
1322 decrementCPEReferenceCount(CPI, CPEMI);
1324 // Now that we have an island to add the CPE to, clone the original CPE and
1325 // add it to the island.
1326 U.HighWaterMark = NewIsland;
1327 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1328 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1329 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1332 // Mark the basic block as aligned as required by the const-pool entry.
1333 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1335 // Increase the size of the island block to account for the new entry.
1336 BBInfo[NewIsland->getNumber()].Size += Size;
1337 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1339 // No existing clone of this CPE is within range.
1340 // We will be generating a new clone. Get a UID for it.
1341 unsigned ID = createPICLabelUId();
1343 // Finally, change the CPI in the instruction operand to be ID.
1344 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1345 if (UserMI->getOperand(i).isCPI()) {
1346 UserMI->getOperand(i).setIndex(ID);
1350 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1351 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1356 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1357 /// sizes and offsets of impacted basic blocks.
1358 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1359 MachineBasicBlock *CPEBB = CPEMI->getParent();
1360 unsigned Size = CPEMI->getOperand(2).getImm();
1361 CPEMI->eraseFromParent();
1362 BBInfo[CPEBB->getNumber()].Size -= Size;
1363 // All succeeding offsets have the current size value added in, fix this.
1364 if (CPEBB->empty()) {
1365 BBInfo[CPEBB->getNumber()].Size = 0;
1367 // This block no longer needs to be aligned.
1368 CPEBB->setAlignment(0);
1370 // Entries are sorted by descending alignment, so realign from the front.
1371 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1373 adjustBBOffsetsAfter(CPEBB);
1374 // An island has only one predecessor BB and one successor BB. Check if
1375 // this BB's predecessor jumps directly to this BB's successor. This
1376 // shouldn't happen currently.
1377 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1378 // FIXME: remove the empty blocks after all the work is done?
1381 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1383 bool MipsConstantIslands::removeUnusedCPEntries() {
1384 unsigned MadeChange = false;
1385 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1386 std::vector<CPEntry> &CPEs = CPEntries[i];
1387 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1388 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1389 removeDeadCPEMI(CPEs[j].CPEMI);
1390 CPEs[j].CPEMI = NULL;
1398 /// isBBInRange - Returns true if the distance between specific MI and
1399 /// specific BB can fit in MI's displacement field.
1400 bool MipsConstantIslands::isBBInRange
1401 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1405 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1406 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1408 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1409 << " from BB#" << MI->getParent()->getNumber()
1410 << " max delta=" << MaxDisp
1411 << " from " << getOffsetOf(MI) << " to " << DestOffset
1412 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1414 if (BrOffset <= DestOffset) {
1415 // Branch before the Dest.
1416 if (DestOffset-BrOffset <= MaxDisp)
1419 if (BrOffset-DestOffset <= MaxDisp)
1425 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1426 /// away to fit in its displacement field.
1427 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1428 MachineInstr *MI = Br.MI;
1429 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1431 // Check to see if the DestBB is already in-range.
1432 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1436 return fixupUnconditionalBr(Br);
1437 return fixupConditionalBr(Br);
1440 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1441 /// too far away to fit in its displacement field. If the LR register has been
1442 /// spilled in the epilogue, then we can use BL to implement a far jump.
1443 /// Otherwise, add an intermediate branch instruction to a branch.
1445 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1446 MachineInstr *MI = Br.MI;
1447 MachineBasicBlock *MBB = MI->getParent();
1448 // Use BL to implement far jump.
1449 Br.MaxDisp = ((1 << 16)-1) * 2;
1450 MI->setDesc(TII->get(Mips::BimmX16));
1451 BBInfo[MBB->getNumber()].Size += 2;
1452 adjustBBOffsetsAfter(MBB);
1456 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1461 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1462 /// far away to fit in its displacement field. It is converted to an inverse
1463 /// conditional branch + an unconditional branch to the destination.
1465 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1466 MachineInstr *MI = Br.MI;
1467 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1469 // Add an unconditional branch to the destination and invert the branch
1470 // condition to jump over it:
1476 unsigned CCReg = 0; // FIXME
1477 unsigned CC=0; //FIXME
1479 // If the branch is at the end of its MBB and that has a fall-through block,
1480 // direct the updated conditional branch to the fall-through block. Otherwise,
1481 // split the MBB before the next instruction.
1482 MachineBasicBlock *MBB = MI->getParent();
1483 MachineInstr *BMI = &MBB->back();
1484 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1488 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1489 BMI->getOpcode() == Br.UncondBr) {
1490 // Last MI in the BB is an unconditional branch. Can we simply invert the
1491 // condition and swap destinations:
1497 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1498 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1499 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1501 BMI->getOperand(0).setMBB(DestBB);
1502 MI->getOperand(0).setMBB(NewDest);
1509 splitBlockBeforeInstr(MI);
1510 // No need for the branch to the next block. We're adding an unconditional
1511 // branch to the destination.
1512 int delta = TII->GetInstSizeInBytes(&MBB->back());
1513 BBInfo[MBB->getNumber()].Size -= delta;
1514 MBB->back().eraseFromParent();
1515 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1517 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1519 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1520 << " also invert condition and change dest. to BB#"
1521 << NextBB->getNumber() << "\n");
1523 // Insert a new conditional branch and a new unconditional branch.
1524 // Also update the ImmBranch as well as adding a new entry for the new branch.
1525 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1526 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1527 Br.MI = &MBB->back();
1528 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1529 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1530 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1531 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1532 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1534 // Remove the old conditional branch. It may or may not still be in MBB.
1535 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1536 MI->eraseFromParent();
1537 adjustBBOffsetsAfter(MBB);
1542 void MipsConstantIslands::prescanForConstants() {
1545 PrescannedForConstants = true;
1546 for (MachineFunction::iterator B =
1547 MF->begin(), E = MF->end(); B != E; ++B) {
1548 for (MachineBasicBlock::instr_iterator I =
1549 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1550 switch(I->getDesc().getOpcode()) {
1551 case Mips::LwConstant32: {
1552 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1553 J = I->getNumOperands();
1554 DEBUG(dbgs() << "num operands " << J << "\n");
1555 MachineOperand& Literal = I->getOperand(1);
1556 if (Literal.isImm()) {
1557 int64_t V = Literal.getImm();
1558 DEBUG(dbgs() << "literal " << V << "\n");
1560 Type::getInt32Ty(MF->getFunction()->getContext());
1561 const Constant *C = ConstantInt::get(Int32Ty, V);
1562 unsigned index = MCP->getConstantPoolIndex(C, 4);
1563 I->getOperand(2).ChangeToImmediate(index);
1564 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1565 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1566 I->RemoveOperand(1);
1567 I->RemoveOperand(1);
1568 I->addOperand(MachineOperand::CreateCPI(index, 0));
1569 I->addOperand(MachineOperand::CreateImm(4));