1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function. This is required due to the
12 // limited pc-relative displacements that ARM has.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "Thumb2InstrInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
38 STATISTIC(NumCPEs, "Number of constpool entries");
39 STATISTIC(NumSplit, "Number of uncond branches inserted");
40 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42 STATISTIC(NumTBs, "Number of table branches generated");
43 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
44 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
45 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
46 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
47 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
51 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
54 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
55 /// add padding such that:
57 /// 1. The result is aligned to 1 << LogAlign.
59 /// 2. No other value of the unknown bits would require more padding.
61 /// This may add more padding than is required to satisfy just one of the
62 /// constraints. It is necessary to compute alignment this way to guarantee
63 /// that we don't underestimate the padding before an aligned block. If the
64 /// real padding before a block is larger than we think, constant pool entries
65 /// may go out of range.
66 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
68 // Add the worst possible padding that the unknown bits could cause.
69 if (KnownBits < LogAlign)
70 Offset += (1u << LogAlign) - (1u << KnownBits);
72 // Then align the result.
73 return RoundUpToAlignment(Offset, 1u << LogAlign);
77 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
78 /// requires constant pool entries to be scattered among the instructions
79 /// inside a function. To do this, it completely ignores the normal LLVM
80 /// constant pool; instead, it places constants wherever it feels like with
81 /// special instructions.
83 /// The terminology used in this pass includes:
84 /// Islands - Clumps of constants placed in the function.
85 /// Water - Potential places where an island could be formed.
86 /// CPE - A constant pool entry that has been placed somewhere, which
87 /// tracks a list of users.
88 class ARMConstantIslands : public MachineFunctionPass {
89 /// BasicBlockInfo - Information about the offset and size of a single
91 struct BasicBlockInfo {
92 /// Offset - Distance from the beginning of the function to the beginning
93 /// of this basic block.
95 /// The offset is always aligned as required by the basic block.
98 /// Size - Size of the basic block in bytes. If the block contains
99 /// inline assembly, this is a worst case estimate.
101 /// The size does not include any alignment padding whether from the
102 /// beginning of the block, or from an aligned jump table at the end.
105 /// KnownBits - The number of low bits in Offset that are known to be
106 /// exact. The remaining bits of Offset are an upper bound.
109 /// Unalign - When non-zero, the block contains instructions (inline asm)
110 /// of unknown size. The real size may be smaller than Size bytes by a
111 /// multiple of 1 << Unalign.
114 /// PostAlign - When non-zero, the block terminator contains a .align
115 /// directive, so the end of the block is aligned to 1 << PostAlign
119 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
122 /// Compute the offset immediately following this block.
123 unsigned postOffset() const {
124 unsigned PO = Offset + Size;
127 // Add alignment padding from the terminator.
128 return WorstCaseAlign(PO, PostAlign, Unalign ? Unalign : KnownBits);
131 /// Compute the number of known low bits of postOffset. If this block
132 /// contains inline asm, the number of known bits drops to the
133 /// instruction alignment. An aligned terminator may increase the number
135 unsigned postKnownBits() const {
136 return std::max(PostAlign, Unalign ? Unalign : KnownBits);
140 std::vector<BasicBlockInfo> BBInfo;
142 /// WaterList - A sorted list of basic blocks where islands could be placed
143 /// (i.e. blocks that don't fall through to the following block, due
144 /// to a return, unreachable, or unconditional branch).
145 std::vector<MachineBasicBlock*> WaterList;
147 /// NewWaterList - The subset of WaterList that was created since the
148 /// previous iteration by inserting unconditional branches.
149 SmallSet<MachineBasicBlock*, 4> NewWaterList;
151 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
153 /// CPUser - One user of a constant pool, keeping the machine instruction
154 /// pointer, the constant pool being referenced, and the max displacement
155 /// allowed from the instruction to the CP. The HighWaterMark records the
156 /// highest basic block where a new CPEntry can be placed. To ensure this
157 /// pass terminates, the CP entries are initially placed at the end of the
158 /// function and then move monotonically to lower addresses. The
159 /// exception to this rule is when the current CP entry for a particular
160 /// CPUser is out of range, but there is another CP entry for the same
161 /// constant value in range. We want to use the existing in-range CP
162 /// entry, but if it later moves out of range, the search for new water
163 /// should resume where it left off. The HighWaterMark is used to record
168 MachineBasicBlock *HighWaterMark;
172 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
173 bool neg, bool soimm)
174 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
175 HighWaterMark = CPEMI->getParent();
179 /// CPUsers - Keep track of all of the machine instructions that use various
180 /// constant pools and their max displacement.
181 std::vector<CPUser> CPUsers;
183 /// CPEntry - One per constant pool entry, keeping the machine instruction
184 /// pointer, the constpool index, and the number of CPUser's which
185 /// reference this entry.
190 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
191 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
194 /// CPEntries - Keep track of all of the constant pool entry machine
195 /// instructions. For each original constpool index (i.e. those that
196 /// existed upon entry to this pass), it keeps a vector of entries.
197 /// Original elements are cloned as we go along; the clones are
198 /// put in the vector of the original element, but have distinct CPIs.
199 std::vector<std::vector<CPEntry> > CPEntries;
201 /// ImmBranch - One per immediate branch, keeping the machine instruction
202 /// pointer, conditional or unconditional, the max displacement,
203 /// and (if isCond is true) the corresponding unconditional branch
207 unsigned MaxDisp : 31;
210 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
211 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
214 /// ImmBranches - Keep track of all the immediate branch instructions.
216 std::vector<ImmBranch> ImmBranches;
218 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
220 SmallVector<MachineInstr*, 4> PushPopMIs;
222 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
223 SmallVector<MachineInstr*, 4> T2JumpTables;
225 /// HasFarJump - True if any far jump instruction has been emitted during
226 /// the branch fix up pass.
229 const ARMInstrInfo *TII;
230 const ARMSubtarget *STI;
231 ARMFunctionInfo *AFI;
237 ARMConstantIslands() : MachineFunctionPass(ID) {}
239 virtual bool runOnMachineFunction(MachineFunction &MF);
241 virtual const char *getPassName() const {
242 return "ARM constant island placement and branch shortening pass";
246 void DoInitialPlacement(MachineFunction &MF,
247 std::vector<MachineInstr*> &CPEMIs);
248 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
249 void JumpTableFunctionScan(MachineFunction &MF);
250 void InitialFunctionScan(MachineFunction &MF,
251 const std::vector<MachineInstr*> &CPEMIs);
252 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
253 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
254 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
255 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
256 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
257 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
258 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
259 MachineBasicBlock *&NewMBB);
260 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
261 void RemoveDeadCPEMI(MachineInstr *CPEMI);
262 bool RemoveUnusedCPEntries();
263 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
264 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
265 bool DoDump = false);
266 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
268 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
269 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
270 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
271 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
272 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
273 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
274 bool UndoLRSpillRestore();
275 bool OptimizeThumb2Instructions(MachineFunction &MF);
276 bool OptimizeThumb2Branches(MachineFunction &MF);
277 bool ReorderThumb2JumpTables(MachineFunction &MF);
278 bool OptimizeThumb2JumpTables(MachineFunction &MF);
279 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
280 MachineBasicBlock *JTBB);
282 void ComputeBlockSize(MachineBasicBlock *MBB);
283 unsigned GetOffsetOf(MachineInstr *MI) const;
285 void verify(MachineFunction &MF);
287 char ARMConstantIslands::ID = 0;
290 /// verify - check BBOffsets, BBSizes, alignment of islands
291 void ARMConstantIslands::verify(MachineFunction &MF) {
293 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
295 MachineBasicBlock *MBB = MBBI;
296 unsigned Align = MBB->getAlignment();
297 unsigned MBBId = MBB->getNumber();
298 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
299 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
301 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
302 CPUser &U = CPUsers[i];
303 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
304 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
305 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
306 UserOffset - CPEOffset;
307 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
312 /// print block size and offset information - debugging
313 void ARMConstantIslands::dumpBBs() {
314 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
315 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
316 << " size " << BBInfo[J].Size << "\n");
320 /// createARMConstantIslandPass - returns an instance of the constpool
322 FunctionPass *llvm::createARMConstantIslandPass() {
323 return new ARMConstantIslands();
326 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
327 MachineConstantPool &MCP = *MF.getConstantPool();
329 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
330 AFI = MF.getInfo<ARMFunctionInfo>();
331 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
333 isThumb = AFI->isThumbFunction();
334 isThumb1 = AFI->isThumb1OnlyFunction();
335 isThumb2 = AFI->isThumb2Function();
339 // Renumber all of the machine basic blocks in the function, guaranteeing that
340 // the numbers agree with the position of the block in the function.
343 // Try to reorder and otherwise adjust the block layout to make good use
344 // of the TB[BH] instructions.
345 bool MadeChange = false;
346 if (isThumb2 && AdjustJumpTableBlocks) {
347 JumpTableFunctionScan(MF);
348 MadeChange |= ReorderThumb2JumpTables(MF);
349 // Data is out of date, so clear it. It'll be re-computed later.
350 T2JumpTables.clear();
351 // Blocks may have shifted around. Keep the numbering up to date.
355 // Thumb1 functions containing constant pools get 4-byte alignment.
356 // This is so we can keep exact track of where the alignment padding goes.
358 // ARM and Thumb2 functions need to be 4-byte aligned.
360 MF.EnsureAlignment(2); // 2 = log2(4)
362 // Perform the initial placement of the constant pool entries. To start with,
363 // we put them all at the end of the function.
364 std::vector<MachineInstr*> CPEMIs;
365 if (!MCP.isEmpty()) {
366 DoInitialPlacement(MF, CPEMIs);
368 MF.EnsureAlignment(2); // 2 = log2(4)
371 /// The next UID to take is the first unused one.
372 AFI->initPICLabelUId(CPEMIs.size());
374 // Do the initial scan of the function, building up information about the
375 // sizes of each block, the location of all the water, and finding all of the
376 // constant pool users.
377 InitialFunctionScan(MF, CPEMIs);
382 /// Remove dead constant pool entries.
383 MadeChange |= RemoveUnusedCPEntries();
385 // Iteratively place constant pool entries and fix up branches until there
387 unsigned NoCPIters = 0, NoBRIters = 0;
389 bool CPChange = false;
390 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
391 CPChange |= HandleConstantPoolUser(MF, i);
392 if (CPChange && ++NoCPIters > 30)
393 llvm_unreachable("Constant Island pass failed to converge!");
396 // Clear NewWaterList now. If we split a block for branches, it should
397 // appear as "new water" for the next iteration of constant pool placement.
398 NewWaterList.clear();
400 bool BRChange = false;
401 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
402 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
403 if (BRChange && ++NoBRIters > 30)
404 llvm_unreachable("Branch Fix Up pass failed to converge!");
407 if (!CPChange && !BRChange)
412 // Shrink 32-bit Thumb2 branch, load, and store instructions.
413 if (isThumb2 && !STI->prefers32BitThumb())
414 MadeChange |= OptimizeThumb2Instructions(MF);
416 // After a while, this might be made debug-only, but it is not expensive.
419 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
420 // undo the spill / restore of LR if possible.
421 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
422 MadeChange |= UndoLRSpillRestore();
424 // Save the mapping between original and cloned constpool entries.
425 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
426 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
427 const CPEntry & CPE = CPEntries[i][j];
428 AFI->recordCPEClone(i, CPE.CPI);
432 DEBUG(errs() << '\n'; dumpBBs());
440 T2JumpTables.clear();
445 /// DoInitialPlacement - Perform the initial placement of the constant pool
446 /// entries. To start with, we put them all at the end of the function.
447 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
448 std::vector<MachineInstr*> &CPEMIs) {
449 // Create the basic block to hold the CPE's.
450 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
453 // Mark the basic block as 4-byte aligned as required by the const-pool.
456 // Add all of the constants from the constant pool to the end block, use an
457 // identity mapping of CPI's to CPE's.
458 const std::vector<MachineConstantPoolEntry> &CPs =
459 MF.getConstantPool()->getConstants();
461 const TargetData &TD = *MF.getTarget().getTargetData();
462 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
463 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
464 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
465 // we would have to pad them out or something so that instructions stay
467 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
468 MachineInstr *CPEMI =
469 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
470 .addImm(i).addConstantPoolIndex(i).addImm(Size);
471 CPEMIs.push_back(CPEMI);
473 // Add a new CPEntry, but no corresponding CPUser yet.
474 std::vector<CPEntry> CPEs;
475 CPEs.push_back(CPEntry(CPEMI, i));
476 CPEntries.push_back(CPEs);
478 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
483 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
484 /// into the block immediately after it.
485 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
486 // Get the next machine basic block in the function.
487 MachineFunction::iterator MBBI = MBB;
488 // Can't fall off end of function.
489 if (llvm::next(MBBI) == MBB->getParent()->end())
492 MachineBasicBlock *NextBB = llvm::next(MBBI);
493 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
494 E = MBB->succ_end(); I != E; ++I)
501 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
502 /// look up the corresponding CPEntry.
503 ARMConstantIslands::CPEntry
504 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
505 const MachineInstr *CPEMI) {
506 std::vector<CPEntry> &CPEs = CPEntries[CPI];
507 // Number of entries per constpool index should be small, just do a
509 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
510 if (CPEs[i].CPEMI == CPEMI)
516 /// JumpTableFunctionScan - Do a scan of the function, building up
517 /// information about the sizes of each block and the locations of all
519 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
520 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
522 MachineBasicBlock &MBB = *MBBI;
524 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
526 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
527 T2JumpTables.push_back(I);
531 /// InitialFunctionScan - Do the initial scan of the function, building up
532 /// information about the sizes of each block, the location of all the water,
533 /// and finding all of the constant pool users.
534 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
535 const std::vector<MachineInstr*> &CPEMIs) {
537 BBInfo.resize(MF.getNumBlockIDs());
539 // First thing, compute the size of all basic blocks, and see if the function
540 // has any inline assembly in it. If so, we have to be conservative about
541 // alignment assumptions, as we don't know for sure the size of any
542 // instructions in the inline assembly.
543 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
546 // The known bits of the entry block offset are determined by the function
548 BBInfo.front().KnownBits = MF.getAlignment();
550 // Compute block offsets and known bits.
551 AdjustBBOffsetsAfter(MF.begin());
553 // Now go back through the instructions and build up our data structures.
554 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
556 MachineBasicBlock &MBB = *MBBI;
558 // If this block doesn't fall through into the next MBB, then this is
559 // 'water' that a constant pool island could be placed.
560 if (!BBHasFallthrough(&MBB))
561 WaterList.push_back(&MBB);
563 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
565 if (I->isDebugValue())
568 int Opc = I->getOpcode();
576 continue; // Ignore other JT branches
578 T2JumpTables.push_back(I);
579 continue; // Does not get an entry in ImmBranches
610 // Record this immediate branch.
611 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
612 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
615 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
616 PushPopMIs.push_back(I);
618 if (Opc == ARM::CONSTPOOL_ENTRY)
621 // Scan the instructions for constant pool operands.
622 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
623 if (I->getOperand(op).isCPI()) {
624 // We found one. The addressing mode tells us the max displacement
625 // from the PC that this instruction permits.
627 // Basic size info comes from the TSFlags field.
631 bool IsSoImm = false;
635 llvm_unreachable("Unknown addressing mode for CP reference!");
638 // Taking the address of a CP entry.
640 // This takes a SoImm, which is 8 bit immediate rotated. We'll
641 // pretend the maximum offset is 255 * 4. Since each instruction
642 // 4 byte wide, this is always correct. We'll check for other
643 // displacements that fits in a SoImm as well.
649 case ARM::t2LEApcrel:
661 Bits = 12; // +-offset_12
667 Scale = 4; // +(offset_8*4)
673 Scale = 4; // +-(offset_8*4)
678 // Remember that this is a user of a CP entry.
679 unsigned CPI = I->getOperand(op).getIndex();
680 MachineInstr *CPEMI = CPEMIs[CPI];
681 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
682 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
684 // Increment corresponding CPEntry reference count.
685 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
686 assert(CPE && "Cannot find a corresponding CPEntry!");
689 // Instructions can only use one CP entry, don't bother scanning the
690 // rest of the operands.
697 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
698 /// This function updates BBInfo directly.
699 void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
700 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
705 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
707 BBI.Size += TII->GetInstSizeInBytes(I);
708 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
709 // The actual size may be smaller, but still a multiple of the instr size.
710 if (I->isInlineAsm())
711 BBI.Unalign = isThumb ? 1 : 2;
714 // tBR_JTr contains a .align 2 directive.
715 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
717 MBB->getParent()->EnsureAlignment(2);
721 /// GetOffsetOf - Return the current offset of the specified machine instruction
722 /// from the start of the function. This offset changes as stuff is moved
723 /// around inside the function.
724 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
725 MachineBasicBlock *MBB = MI->getParent();
727 // The offset is composed of two things: the sum of the sizes of all MBB's
728 // before this instruction's block, and the offset from the start of the block
730 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
732 // Sum instructions before MI in MBB.
733 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
734 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
735 if (&*I == MI) return Offset;
736 Offset += TII->GetInstSizeInBytes(I);
740 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
742 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
743 const MachineBasicBlock *RHS) {
744 return LHS->getNumber() < RHS->getNumber();
747 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
748 /// machine function, it upsets all of the block numbers. Renumber the blocks
749 /// and update the arrays that parallel this numbering.
750 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
751 // Renumber the MBB's to keep them consecutive.
752 NewBB->getParent()->RenumberBlocks(NewBB);
754 // Insert an entry into BBInfo to align it properly with the (newly
755 // renumbered) block numbers.
756 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
758 // Next, update WaterList. Specifically, we need to add NewMBB as having
759 // available water after it.
761 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
763 WaterList.insert(IP, NewBB);
767 /// Split the basic block containing MI into two blocks, which are joined by
768 /// an unconditional branch. Update data structures and renumber blocks to
769 /// account for this change and returns the newly created block.
770 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
771 MachineBasicBlock *OrigBB = MI->getParent();
772 MachineFunction &MF = *OrigBB->getParent();
774 // Create a new MBB for the code after the OrigBB.
775 MachineBasicBlock *NewBB =
776 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
777 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
778 MF.insert(MBBI, NewBB);
780 // Splice the instructions starting with MI over to NewBB.
781 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
783 // Add an unconditional branch from OrigBB to NewBB.
784 // Note the new unconditional branch is not being recorded.
785 // There doesn't seem to be meaningful DebugInfo available; this doesn't
786 // correspond to anything in the source.
787 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
789 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
791 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
792 .addImm(ARMCC::AL).addReg(0);
795 // Update the CFG. All succs of OrigBB are now succs of NewBB.
796 NewBB->transferSuccessors(OrigBB);
798 // OrigBB branches to NewBB.
799 OrigBB->addSuccessor(NewBB);
801 // Update internal data structures to account for the newly inserted MBB.
802 // This is almost the same as UpdateForInsertedWaterBlock, except that
803 // the Water goes after OrigBB, not NewBB.
804 MF.RenumberBlocks(NewBB);
806 // Insert an entry into BBInfo to align it properly with the (newly
807 // renumbered) block numbers.
808 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
810 // Next, update WaterList. Specifically, we need to add OrigMBB as having
811 // available water after it (but not if it's already there, which happens
812 // when splitting before a conditional branch that is followed by an
813 // unconditional branch - in that case we want to insert NewBB).
815 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
817 MachineBasicBlock* WaterBB = *IP;
818 if (WaterBB == OrigBB)
819 WaterList.insert(llvm::next(IP), NewBB);
821 WaterList.insert(IP, OrigBB);
822 NewWaterList.insert(OrigBB);
824 // Figure out how large the OrigBB is. As the first half of the original
825 // block, it cannot contain a tablejump. The size includes
826 // the new jump we added. (It should be possible to do this without
827 // recounting everything, but it's very confusing, and this is rarely
829 ComputeBlockSize(OrigBB);
831 // Figure out how large the NewMBB is. As the second half of the original
832 // block, it may contain a tablejump.
833 ComputeBlockSize(NewBB);
835 // All BBOffsets following these blocks must be modified.
836 AdjustBBOffsetsAfter(OrigBB);
841 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
842 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
843 /// constant pool entry).
844 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
845 unsigned TrialOffset, unsigned MaxDisp,
846 bool NegativeOK, bool IsSoImm) {
847 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
848 // purposes of the displacement computation; compensate for that here.
849 // Effectively, the valid range of displacements is 2 bytes smaller for such
851 unsigned TotalAdj = 0;
852 if (isThumb && UserOffset%4 !=0) {
856 // CPEs will be rounded up to a multiple of 4.
857 if (isThumb && TrialOffset%4 != 0) {
862 // In Thumb2 mode, later branch adjustments can shift instructions up and
863 // cause alignment change. In the worst case scenario this can cause the
864 // user's effective address to be subtracted by 2 and the CPE's address to
866 if (isThumb2 && TotalAdj != 4)
867 MaxDisp -= (4 - TotalAdj);
869 if (UserOffset <= TrialOffset) {
870 // User before the Trial.
871 if (TrialOffset - UserOffset <= MaxDisp)
873 // FIXME: Make use full range of soimm values.
874 } else if (NegativeOK) {
875 if (UserOffset - TrialOffset <= MaxDisp)
877 // FIXME: Make use full range of soimm values.
882 /// WaterIsInRange - Returns true if a CPE placed after the specified
883 /// Water (a basic block) will be in range for the specific MI.
885 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
886 MachineBasicBlock* Water, CPUser &U) {
887 unsigned MaxDisp = U.MaxDisp;
888 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
890 // If the CPE is to be inserted before the instruction, that will raise
891 // the offset of the instruction.
892 if (CPEOffset < UserOffset)
893 UserOffset += U.CPEMI->getOperand(2).getImm();
895 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
898 /// CPEIsInRange - Returns true if the distance between specific MI and
899 /// specific ConstPool entry instruction can fit in MI's displacement field.
900 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
901 MachineInstr *CPEMI, unsigned MaxDisp,
902 bool NegOk, bool DoDump) {
903 unsigned CPEOffset = GetOffsetOf(CPEMI);
904 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
907 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
908 << " max delta=" << MaxDisp
909 << " insn address=" << UserOffset
910 << " CPE address=" << CPEOffset
911 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
914 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
918 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
919 /// unconditionally branches to its only successor.
920 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
921 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
924 MachineBasicBlock *Succ = *MBB->succ_begin();
925 MachineBasicBlock *Pred = *MBB->pred_begin();
926 MachineInstr *PredMI = &Pred->back();
927 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
928 || PredMI->getOpcode() == ARM::t2B)
929 return PredMI->getOperand(0).getMBB() == Succ;
934 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
935 MachineFunction *MF = BB->getParent();
936 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
937 // Get the offset and known bits at the end of the layout predecessor.
938 unsigned Offset = BBInfo[i - 1].postOffset();
939 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
941 // Add padding before an aligned block. This may teach us more bits.
942 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
943 Offset = WorstCaseAlign(Offset, Align, KnownBits);
944 KnownBits = std::max(KnownBits, Align);
947 // This is where block i begins.
948 BBInfo[i].Offset = Offset;
949 BBInfo[i].KnownBits = KnownBits;
953 /// DecrementOldEntry - find the constant pool entry with index CPI
954 /// and instruction CPEMI, and decrement its refcount. If the refcount
955 /// becomes 0 remove the entry and instruction. Returns true if we removed
956 /// the entry, false if we didn't.
958 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
959 // Find the old entry. Eliminate it if it is no longer used.
960 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
961 assert(CPE && "Unexpected!");
962 if (--CPE->RefCount == 0) {
963 RemoveDeadCPEMI(CPEMI);
971 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
972 /// if not, see if an in-range clone of the CPE is in range, and if so,
973 /// change the data structures so the user references the clone. Returns:
974 /// 0 = no existing entry found
975 /// 1 = entry found, and there were no code insertions or deletions
976 /// 2 = entry found, and there were code insertions or deletions
977 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
979 MachineInstr *UserMI = U.MI;
980 MachineInstr *CPEMI = U.CPEMI;
982 // Check to see if the CPE is already in-range.
983 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
984 DEBUG(errs() << "In range\n");
988 // No. Look for previously created clones of the CPE that are in range.
989 unsigned CPI = CPEMI->getOperand(1).getIndex();
990 std::vector<CPEntry> &CPEs = CPEntries[CPI];
991 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
992 // We already tried this one
993 if (CPEs[i].CPEMI == CPEMI)
995 // Removing CPEs can leave empty entries, skip
996 if (CPEs[i].CPEMI == NULL)
998 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
999 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1000 << CPEs[i].CPI << "\n");
1001 // Point the CPUser node to the replacement
1002 U.CPEMI = CPEs[i].CPEMI;
1003 // Change the CPI in the instruction operand to refer to the clone.
1004 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1005 if (UserMI->getOperand(j).isCPI()) {
1006 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1009 // Adjust the refcount of the clone...
1011 // ...and the original. If we didn't remove the old entry, none of the
1012 // addresses changed, so we don't need another pass.
1013 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1019 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1020 /// the specific unconditional branch instruction.
1021 static inline unsigned getUnconditionalBrDisp(int Opc) {
1024 return ((1<<10)-1)*2;
1026 return ((1<<23)-1)*2;
1031 return ((1<<23)-1)*4;
1034 /// LookForWater - Look for an existing entry in the WaterList in which
1035 /// we can place the CPE referenced from U so it's within range of U's MI.
1036 /// Returns true if found, false if not. If it returns true, WaterIter
1037 /// is set to the WaterList entry. For Thumb, prefer water that will not
1038 /// introduce padding to water that will. To ensure that this pass
1039 /// terminates, the CPE location for a particular CPUser is only allowed to
1040 /// move to a lower address, so search backward from the end of the list and
1041 /// prefer the first water that is in range.
1042 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1043 water_iterator &WaterIter) {
1044 if (WaterList.empty())
1047 bool FoundWaterThatWouldPad = false;
1048 water_iterator IPThatWouldPad;
1049 for (water_iterator IP = prior(WaterList.end()),
1050 B = WaterList.begin();; --IP) {
1051 MachineBasicBlock* WaterBB = *IP;
1052 // Check if water is in range and is either at a lower address than the
1053 // current "high water mark" or a new water block that was created since
1054 // the previous iteration by inserting an unconditional branch. In the
1055 // latter case, we want to allow resetting the high water mark back to
1056 // this new water since we haven't seen it before. Inserting branches
1057 // should be relatively uncommon and when it does happen, we want to be
1058 // sure to take advantage of it for all the CPEs near that block, so that
1059 // we don't insert more branches than necessary.
1060 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1061 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1062 NewWaterList.count(WaterBB))) {
1063 unsigned WBBId = WaterBB->getNumber();
1064 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1065 // This is valid Water, but would introduce padding. Remember
1066 // it in case we don't find any Water that doesn't do this.
1067 if (!FoundWaterThatWouldPad) {
1068 FoundWaterThatWouldPad = true;
1069 IPThatWouldPad = IP;
1079 if (FoundWaterThatWouldPad) {
1080 WaterIter = IPThatWouldPad;
1086 /// CreateNewWater - No existing WaterList entry will work for
1087 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1088 /// block is used if in range, and the conditional branch munged so control
1089 /// flow is correct. Otherwise the block is split to create a hole with an
1090 /// unconditional branch around it. In either case NewMBB is set to a
1091 /// block following which the new island can be inserted (the WaterList
1092 /// is not adjusted).
1093 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1094 unsigned UserOffset,
1095 MachineBasicBlock *&NewMBB) {
1096 CPUser &U = CPUsers[CPUserIndex];
1097 MachineInstr *UserMI = U.MI;
1098 MachineInstr *CPEMI = U.CPEMI;
1099 MachineBasicBlock *UserMBB = UserMI->getParent();
1100 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
1102 // If the block does not end in an unconditional branch already, and if the
1103 // end of the block is within range, make new water there. (The addition
1104 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1105 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1106 // inside OffsetIsInRange.
1107 if (BBHasFallthrough(UserMBB) &&
1108 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1109 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1110 DEBUG(errs() << "Split at end of block\n");
1111 if (&UserMBB->back() == UserMI)
1112 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1113 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1114 // Add an unconditional branch from UserMBB to fallthrough block.
1115 // Record it for branch lengthening; this new branch will not get out of
1116 // range, but if the preceding conditional branch is out of range, the
1117 // targets will be exchanged, and the altered branch may be out of
1118 // range, so the machinery has to know about it.
1119 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1121 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1123 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1124 .addImm(ARMCC::AL).addReg(0);
1125 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1126 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1127 MaxDisp, false, UncondBr));
1128 int delta = isThumb1 ? 2 : 4;
1129 BBInfo[UserMBB->getNumber()].Size += delta;
1130 AdjustBBOffsetsAfter(UserMBB);
1132 // What a big block. Find a place within the block to split it.
1133 // This is a little tricky on Thumb1 since instructions are 2 bytes
1134 // and constant pool entries are 4 bytes: if instruction I references
1135 // island CPE, and instruction I+1 references CPE', it will
1136 // not work well to put CPE as far forward as possible, since then
1137 // CPE' cannot immediately follow it (that location is 2 bytes
1138 // farther away from I+1 than CPE was from I) and we'd need to create
1139 // a new island. So, we make a first guess, then walk through the
1140 // instructions between the one currently being looked at and the
1141 // possible insertion point, and make sure any other instructions
1142 // that reference CPEs will be able to use the same island area;
1143 // if not, we back up the insertion point.
1145 // The 4 in the following is for the unconditional branch we'll be
1146 // inserting (allows for long branch on Thumb1). Alignment of the
1147 // island is handled inside OffsetIsInRange.
1148 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1149 // This could point off the end of the block if we've already got
1150 // constant pool entries following this block; only the last one is
1151 // in the water list. Back past any possible branches (allow for a
1152 // conditional and a maximally long unconditional).
1153 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1154 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1156 unsigned EndInsertOffset = BaseInsertOffset +
1157 CPEMI->getOperand(2).getImm();
1158 MachineBasicBlock::iterator MI = UserMI;
1160 unsigned CPUIndex = CPUserIndex+1;
1161 unsigned NumCPUsers = CPUsers.size();
1162 MachineInstr *LastIT = 0;
1163 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1164 Offset < BaseInsertOffset;
1165 Offset += TII->GetInstSizeInBytes(MI),
1166 MI = llvm::next(MI)) {
1167 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1168 CPUser &U = CPUsers[CPUIndex];
1169 if (!OffsetIsInRange(Offset, EndInsertOffset,
1170 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1171 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1172 EndInsertOffset -= (isThumb1 ? 2 : 4);
1174 // This is overly conservative, as we don't account for CPEMIs
1175 // being reused within the block, but it doesn't matter much.
1176 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1180 // Remember the last IT instruction.
1181 if (MI->getOpcode() == ARM::t2IT)
1185 DEBUG(errs() << "Split in middle of big block\n");
1188 // Avoid splitting an IT block.
1190 unsigned PredReg = 0;
1191 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1192 if (CC != ARMCC::AL)
1195 NewMBB = SplitBlockBeforeInstr(MI);
1199 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1200 /// is out-of-range. If so, pick up the constant pool value and move it some
1201 /// place in-range. Return true if we changed any addresses (thus must run
1202 /// another pass of branch lengthening), false otherwise.
1203 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1204 unsigned CPUserIndex) {
1205 CPUser &U = CPUsers[CPUserIndex];
1206 MachineInstr *UserMI = U.MI;
1207 MachineInstr *CPEMI = U.CPEMI;
1208 unsigned CPI = CPEMI->getOperand(1).getIndex();
1209 unsigned Size = CPEMI->getOperand(2).getImm();
1210 // Compute this only once, it's expensive. The 4 or 8 is the value the
1211 // hardware keeps in the PC.
1212 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1214 // See if the current entry is within range, or there is a clone of it
1216 int result = LookForExistingCPEntry(U, UserOffset);
1217 if (result==1) return false;
1218 else if (result==2) return true;
1220 // No existing clone of this CPE is within range.
1221 // We will be generating a new clone. Get a UID for it.
1222 unsigned ID = AFI->createPICLabelUId();
1224 // Look for water where we can place this CPE.
1225 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1226 MachineBasicBlock *NewMBB;
1228 if (LookForWater(U, UserOffset, IP)) {
1229 DEBUG(errs() << "found water in range\n");
1230 MachineBasicBlock *WaterBB = *IP;
1232 // If the original WaterList entry was "new water" on this iteration,
1233 // propagate that to the new island. This is just keeping NewWaterList
1234 // updated to match the WaterList, which will be updated below.
1235 if (NewWaterList.count(WaterBB)) {
1236 NewWaterList.erase(WaterBB);
1237 NewWaterList.insert(NewIsland);
1239 // The new CPE goes before the following block (NewMBB).
1240 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1244 DEBUG(errs() << "No water found\n");
1245 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1247 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1248 // called while handling branches so that the water will be seen on the
1249 // next iteration for constant pools, but in this context, we don't want
1250 // it. Check for this so it will be removed from the WaterList.
1251 // Also remove any entry from NewWaterList.
1252 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1253 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1254 if (IP != WaterList.end())
1255 NewWaterList.erase(WaterBB);
1257 // We are adding new water. Update NewWaterList.
1258 NewWaterList.insert(NewIsland);
1261 // Remove the original WaterList entry; we want subsequent insertions in
1262 // this vicinity to go after the one we're about to insert. This
1263 // considerably reduces the number of times we have to move the same CPE
1264 // more than once and is also important to ensure the algorithm terminates.
1265 if (IP != WaterList.end())
1266 WaterList.erase(IP);
1268 // Okay, we know we can put an island before NewMBB now, do it!
1269 MF.insert(NewMBB, NewIsland);
1271 // Update internal data structures to account for the newly inserted MBB.
1272 UpdateForInsertedWaterBlock(NewIsland);
1274 // Decrement the old entry, and remove it if refcount becomes 0.
1275 DecrementOldEntry(CPI, CPEMI);
1277 // Now that we have an island to add the CPE to, clone the original CPE and
1278 // add it to the island.
1279 U.HighWaterMark = NewIsland;
1280 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1281 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1282 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1285 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1286 NewIsland->setAlignment(2);
1288 // Increase the size of the island block to account for the new entry.
1289 BBInfo[NewIsland->getNumber()].Size += Size;
1290 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1292 // Finally, change the CPI in the instruction operand to be ID.
1293 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1294 if (UserMI->getOperand(i).isCPI()) {
1295 UserMI->getOperand(i).setIndex(ID);
1299 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1300 << '\t' << *UserMI);
1305 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1306 /// sizes and offsets of impacted basic blocks.
1307 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1308 MachineBasicBlock *CPEBB = CPEMI->getParent();
1309 unsigned Size = CPEMI->getOperand(2).getImm();
1310 CPEMI->eraseFromParent();
1311 BBInfo[CPEBB->getNumber()].Size -= Size;
1312 // All succeeding offsets have the current size value added in, fix this.
1313 if (CPEBB->empty()) {
1314 // In thumb1 mode, the size of island may be padded by two to compensate for
1315 // the alignment requirement. Then it will now be 2 when the block is
1316 // empty, so fix this.
1317 // All succeeding offsets have the current size value added in, fix this.
1318 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1319 Size += BBInfo[CPEBB->getNumber()].Size;
1320 BBInfo[CPEBB->getNumber()].Size = 0;
1323 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1324 CPEBB->setAlignment(0);
1326 AdjustBBOffsetsAfter(CPEBB);
1327 // An island has only one predecessor BB and one successor BB. Check if
1328 // this BB's predecessor jumps directly to this BB's successor. This
1329 // shouldn't happen currently.
1330 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1331 // FIXME: remove the empty blocks after all the work is done?
1334 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1336 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1337 unsigned MadeChange = false;
1338 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1339 std::vector<CPEntry> &CPEs = CPEntries[i];
1340 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1341 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1342 RemoveDeadCPEMI(CPEs[j].CPEMI);
1343 CPEs[j].CPEMI = NULL;
1351 /// BBIsInRange - Returns true if the distance between specific MI and
1352 /// specific BB can fit in MI's displacement field.
1353 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1355 unsigned PCAdj = isThumb ? 4 : 8;
1356 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1357 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1359 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1360 << " from BB#" << MI->getParent()->getNumber()
1361 << " max delta=" << MaxDisp
1362 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1363 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1365 if (BrOffset <= DestOffset) {
1366 // Branch before the Dest.
1367 if (DestOffset-BrOffset <= MaxDisp)
1370 if (BrOffset-DestOffset <= MaxDisp)
1376 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1377 /// away to fit in its displacement field.
1378 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1379 MachineInstr *MI = Br.MI;
1380 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1382 // Check to see if the DestBB is already in-range.
1383 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1387 return FixUpUnconditionalBr(MF, Br);
1388 return FixUpConditionalBr(MF, Br);
1391 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1392 /// too far away to fit in its displacement field. If the LR register has been
1393 /// spilled in the epilogue, then we can use BL to implement a far jump.
1394 /// Otherwise, add an intermediate branch instruction to a branch.
1396 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1397 MachineInstr *MI = Br.MI;
1398 MachineBasicBlock *MBB = MI->getParent();
1400 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1402 // Use BL to implement far jump.
1403 Br.MaxDisp = (1 << 21) * 2;
1404 MI->setDesc(TII->get(ARM::tBfar));
1405 BBInfo[MBB->getNumber()].Size += 2;
1406 AdjustBBOffsetsAfter(MBB);
1410 DEBUG(errs() << " Changed B to long jump " << *MI);
1415 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1416 /// far away to fit in its displacement field. It is converted to an inverse
1417 /// conditional branch + an unconditional branch to the destination.
1419 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1420 MachineInstr *MI = Br.MI;
1421 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1423 // Add an unconditional branch to the destination and invert the branch
1424 // condition to jump over it:
1430 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1431 CC = ARMCC::getOppositeCondition(CC);
1432 unsigned CCReg = MI->getOperand(2).getReg();
1434 // If the branch is at the end of its MBB and that has a fall-through block,
1435 // direct the updated conditional branch to the fall-through block. Otherwise,
1436 // split the MBB before the next instruction.
1437 MachineBasicBlock *MBB = MI->getParent();
1438 MachineInstr *BMI = &MBB->back();
1439 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1443 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1444 BMI->getOpcode() == Br.UncondBr) {
1445 // Last MI in the BB is an unconditional branch. Can we simply invert the
1446 // condition and swap destinations:
1452 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1453 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1454 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1456 BMI->getOperand(0).setMBB(DestBB);
1457 MI->getOperand(0).setMBB(NewDest);
1458 MI->getOperand(1).setImm(CC);
1465 SplitBlockBeforeInstr(MI);
1466 // No need for the branch to the next block. We're adding an unconditional
1467 // branch to the destination.
1468 int delta = TII->GetInstSizeInBytes(&MBB->back());
1469 BBInfo[MBB->getNumber()].Size -= delta;
1470 MBB->back().eraseFromParent();
1471 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1473 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1475 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1476 << " also invert condition and change dest. to BB#"
1477 << NextBB->getNumber() << "\n");
1479 // Insert a new conditional branch and a new unconditional branch.
1480 // Also update the ImmBranch as well as adding a new entry for the new branch.
1481 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1482 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1483 Br.MI = &MBB->back();
1484 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1486 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1487 .addImm(ARMCC::AL).addReg(0);
1489 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1490 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1491 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1492 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1494 // Remove the old conditional branch. It may or may not still be in MBB.
1495 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1496 MI->eraseFromParent();
1497 AdjustBBOffsetsAfter(MBB);
1501 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1502 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1503 /// to do this if tBfar is not used.
1504 bool ARMConstantIslands::UndoLRSpillRestore() {
1505 bool MadeChange = false;
1506 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1507 MachineInstr *MI = PushPopMIs[i];
1508 // First two operands are predicates.
1509 if (MI->getOpcode() == ARM::tPOP_RET &&
1510 MI->getOperand(2).getReg() == ARM::PC &&
1511 MI->getNumExplicitOperands() == 3) {
1512 // Create the new insn and copy the predicate from the old.
1513 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1514 .addOperand(MI->getOperand(0))
1515 .addOperand(MI->getOperand(1));
1516 MI->eraseFromParent();
1523 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1524 bool MadeChange = false;
1526 // Shrink ADR and LDR from constantpool.
1527 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1528 CPUser &U = CPUsers[i];
1529 unsigned Opcode = U.MI->getOpcode();
1530 unsigned NewOpc = 0;
1535 case ARM::t2LEApcrel:
1536 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1537 NewOpc = ARM::tLEApcrel;
1543 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1544 NewOpc = ARM::tLDRpci;
1554 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1555 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1556 // FIXME: Check if offset is multiple of scale if scale is not 4.
1557 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1558 U.MI->setDesc(TII->get(NewOpc));
1559 MachineBasicBlock *MBB = U.MI->getParent();
1560 BBInfo[MBB->getNumber()].Size -= 2;
1561 AdjustBBOffsetsAfter(MBB);
1567 MadeChange |= OptimizeThumb2Branches(MF);
1568 MadeChange |= OptimizeThumb2JumpTables(MF);
1572 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1573 bool MadeChange = false;
1575 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1576 ImmBranch &Br = ImmBranches[i];
1577 unsigned Opcode = Br.MI->getOpcode();
1578 unsigned NewOpc = 0;
1596 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1597 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1598 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1599 Br.MI->setDesc(TII->get(NewOpc));
1600 MachineBasicBlock *MBB = Br.MI->getParent();
1601 BBInfo[MBB->getNumber()].Size -= 2;
1602 AdjustBBOffsetsAfter(MBB);
1608 Opcode = Br.MI->getOpcode();
1609 if (Opcode != ARM::tBcc)
1613 unsigned PredReg = 0;
1614 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1615 if (Pred == ARMCC::EQ)
1617 else if (Pred == ARMCC::NE)
1618 NewOpc = ARM::tCBNZ;
1621 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1622 // Check if the distance is within 126. Subtract starting offset by 2
1623 // because the cmp will be eliminated.
1624 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1625 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1626 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1627 MachineBasicBlock::iterator CmpMI = Br.MI;
1628 if (CmpMI != Br.MI->getParent()->begin()) {
1630 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1631 unsigned Reg = CmpMI->getOperand(0).getReg();
1632 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1633 if (Pred == ARMCC::AL &&
1634 CmpMI->getOperand(1).getImm() == 0 &&
1635 isARMLowRegister(Reg)) {
1636 MachineBasicBlock *MBB = Br.MI->getParent();
1637 MachineInstr *NewBR =
1638 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1639 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1640 CmpMI->eraseFromParent();
1641 Br.MI->eraseFromParent();
1643 BBInfo[MBB->getNumber()].Size -= 2;
1644 AdjustBBOffsetsAfter(MBB);
1656 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1657 /// jumptables when it's possible.
1658 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1659 bool MadeChange = false;
1661 // FIXME: After the tables are shrunk, can we get rid some of the
1662 // constantpool tables?
1663 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1664 if (MJTI == 0) return false;
1666 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1667 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1668 MachineInstr *MI = T2JumpTables[i];
1669 const MCInstrDesc &MCID = MI->getDesc();
1670 unsigned NumOps = MCID.getNumOperands();
1671 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1672 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1673 unsigned JTI = JTOP.getIndex();
1674 assert(JTI < JT.size());
1677 bool HalfWordOk = true;
1678 unsigned JTOffset = GetOffsetOf(MI) + 4;
1679 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1680 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1681 MachineBasicBlock *MBB = JTBBs[j];
1682 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1683 // Negative offset is not ok. FIXME: We should change BB layout to make
1684 // sure all the branches are forward.
1685 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1687 unsigned TBHLimit = ((1<<16)-1)*2;
1688 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1690 if (!ByteOk && !HalfWordOk)
1694 if (ByteOk || HalfWordOk) {
1695 MachineBasicBlock *MBB = MI->getParent();
1696 unsigned BaseReg = MI->getOperand(0).getReg();
1697 bool BaseRegKill = MI->getOperand(0).isKill();
1700 unsigned IdxReg = MI->getOperand(1).getReg();
1701 bool IdxRegKill = MI->getOperand(1).isKill();
1703 // Scan backwards to find the instruction that defines the base
1704 // register. Due to post-RA scheduling, we can't count on it
1705 // immediately preceding the branch instruction.
1706 MachineBasicBlock::iterator PrevI = MI;
1707 MachineBasicBlock::iterator B = MBB->begin();
1708 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1711 // If for some reason we didn't find it, we can't do anything, so
1712 // just skip this one.
1713 if (!PrevI->definesRegister(BaseReg))
1716 MachineInstr *AddrMI = PrevI;
1718 // Examine the instruction that calculates the jumptable entry address.
1719 // Make sure it only defines the base register and kills any uses
1720 // other than the index register.
1721 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1722 const MachineOperand &MO = AddrMI->getOperand(k);
1723 if (!MO.isReg() || !MO.getReg())
1725 if (MO.isDef() && MO.getReg() != BaseReg) {
1729 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1737 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1738 // that gave us the initial base register definition.
1739 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1742 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1743 // to delete it as well.
1744 MachineInstr *LeaMI = PrevI;
1745 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1746 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1747 LeaMI->getOperand(0).getReg() != BaseReg)
1753 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1754 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1755 .addReg(IdxReg, getKillRegState(IdxRegKill))
1756 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1757 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1758 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1759 // is 2-byte aligned. For now, asm printer will fix it up.
1760 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1761 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1762 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1763 OrigSize += TII->GetInstSizeInBytes(MI);
1765 AddrMI->eraseFromParent();
1766 LeaMI->eraseFromParent();
1767 MI->eraseFromParent();
1769 int delta = OrigSize - NewSize;
1770 BBInfo[MBB->getNumber()].Size -= delta;
1771 AdjustBBOffsetsAfter(MBB);
1781 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1782 /// jump tables always branch forwards, since that's what tbb and tbh need.
1783 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1784 bool MadeChange = false;
1786 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1787 if (MJTI == 0) return false;
1789 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1790 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1791 MachineInstr *MI = T2JumpTables[i];
1792 const MCInstrDesc &MCID = MI->getDesc();
1793 unsigned NumOps = MCID.getNumOperands();
1794 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1795 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1796 unsigned JTI = JTOP.getIndex();
1797 assert(JTI < JT.size());
1799 // We prefer if target blocks for the jump table come after the jump
1800 // instruction so we can use TB[BH]. Loop through the target blocks
1801 // and try to adjust them such that that's true.
1802 int JTNumber = MI->getParent()->getNumber();
1803 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1804 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1805 MachineBasicBlock *MBB = JTBBs[j];
1806 int DTNumber = MBB->getNumber();
1808 if (DTNumber < JTNumber) {
1809 // The destination precedes the switch. Try to move the block forward
1810 // so we have a positive offset.
1811 MachineBasicBlock *NewBB =
1812 AdjustJTTargetBlockForward(MBB, MI->getParent());
1814 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1823 MachineBasicBlock *ARMConstantIslands::
1824 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1826 MachineFunction &MF = *BB->getParent();
1828 // If the destination block is terminated by an unconditional branch,
1829 // try to move it; otherwise, create a new block following the jump
1830 // table that branches back to the actual target. This is a very simple
1831 // heuristic. FIXME: We can definitely improve it.
1832 MachineBasicBlock *TBB = 0, *FBB = 0;
1833 SmallVector<MachineOperand, 4> Cond;
1834 SmallVector<MachineOperand, 4> CondPrior;
1835 MachineFunction::iterator BBi = BB;
1836 MachineFunction::iterator OldPrior = prior(BBi);
1838 // If the block terminator isn't analyzable, don't try to move the block
1839 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1841 // If the block ends in an unconditional branch, move it. The prior block
1842 // has to have an analyzable terminator for us to move this one. Be paranoid
1843 // and make sure we're not trying to move the entry block of the function.
1844 if (!B && Cond.empty() && BB != MF.begin() &&
1845 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1846 BB->moveAfter(JTBB);
1847 OldPrior->updateTerminator();
1848 BB->updateTerminator();
1849 // Update numbering to account for the block being moved.
1850 MF.RenumberBlocks();
1855 // Create a new MBB for the code after the jump BB.
1856 MachineBasicBlock *NewBB =
1857 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1858 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1859 MF.insert(MBBI, NewBB);
1861 // Add an unconditional branch from NewBB to BB.
1862 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1863 // correspond directly to anything in the source.
1864 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1865 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1866 .addImm(ARMCC::AL).addReg(0);
1868 // Update internal data structures to account for the newly inserted MBB.
1869 MF.RenumberBlocks(NewBB);
1872 NewBB->addSuccessor(BB);
1873 JTBB->removeSuccessor(BB);
1874 JTBB->addSuccessor(NewBB);