1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
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 "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(NumCPEs
, "Number of constpool entries");
33 STATISTIC(NumSplit
, "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed
, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed
, "Number of uncond branches fixed");
38 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
41 /// constant pool; instead, it places constants wherever it feels like with
42 /// special instructions.
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands
: public MachineFunctionPass
{
50 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51 /// by MBB Number. The two-byte pads required for Thumb alignment are
52 /// counted as part of the following block (i.e., the offset and size for
53 /// a padded block will both be ==2 mod 4).
54 std::vector
<unsigned> BBSizes
;
56 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
57 /// The two-byte pads required for Thumb alignment are counted as part of
58 /// the following block.
59 std::vector
<unsigned> BBOffsets
;
61 /// WaterList - A sorted list of basic blocks where islands could be placed
62 /// (i.e. blocks that don't fall through to the following block, due
63 /// to a return, unreachable, or unconditional branch).
64 std::vector
<MachineBasicBlock
*> WaterList
;
66 /// CPUser - One user of a constant pool, keeping the machine instruction
67 /// pointer, the constant pool being referenced, and the max displacement
68 /// allowed from the instruction to the CP.
73 CPUser(MachineInstr
*mi
, MachineInstr
*cpemi
, unsigned maxdisp
)
74 : MI(mi
), CPEMI(cpemi
), MaxDisp(maxdisp
) {}
77 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
79 std::vector
<CPUser
> CPUsers
;
81 /// CPEntry - One per constant pool entry, keeping the machine instruction
82 /// pointer, the constpool index, and the number of CPUser's which
83 /// reference this entry.
88 CPEntry(MachineInstr
*cpemi
, unsigned cpi
, unsigned rc
= 0)
89 : CPEMI(cpemi
), CPI(cpi
), RefCount(rc
) {}
92 /// CPEntries - Keep track of all of the constant pool entry machine
93 /// instructions. For each original constpool index (i.e. those that
94 /// existed upon entry to this pass), it keeps a vector of entries.
95 /// Original elements are cloned as we go along; the clones are
96 /// put in the vector of the original element, but have distinct CPIs.
97 std::vector
<std::vector
<CPEntry
> > CPEntries
;
99 /// ImmBranch - One per immediate branch, keeping the machine instruction
100 /// pointer, conditional or unconditional, the max displacement,
101 /// and (if isCond is true) the corresponding unconditional branch
105 unsigned MaxDisp
: 31;
108 ImmBranch(MachineInstr
*mi
, unsigned maxdisp
, bool cond
, int ubr
)
109 : MI(mi
), MaxDisp(maxdisp
), isCond(cond
), UncondBr(ubr
) {}
112 /// ImmBranches - Keep track of all the immediate branch instructions.
114 std::vector
<ImmBranch
> ImmBranches
;
116 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
118 SmallVector
<MachineInstr
*, 4> PushPopMIs
;
120 /// HasFarJump - True if any far jump instruction has been emitted during
121 /// the branch fix up pass.
124 const TargetInstrInfo
*TII
;
125 ARMFunctionInfo
*AFI
;
129 ARMConstantIslands() : MachineFunctionPass(&ID
) {}
131 virtual bool runOnMachineFunction(MachineFunction
&Fn
);
133 virtual const char *getPassName() const {
134 return "ARM constant island placement and branch shortening pass";
138 void DoInitialPlacement(MachineFunction
&Fn
,
139 std::vector
<MachineInstr
*> &CPEMIs
);
140 CPEntry
*findConstPoolEntry(unsigned CPI
, const MachineInstr
*CPEMI
);
141 void InitialFunctionScan(MachineFunction
&Fn
,
142 const std::vector
<MachineInstr
*> &CPEMIs
);
143 MachineBasicBlock
*SplitBlockBeforeInstr(MachineInstr
*MI
);
144 void UpdateForInsertedWaterBlock(MachineBasicBlock
*NewBB
);
145 void AdjustBBOffsetsAfter(MachineBasicBlock
*BB
, int delta
);
146 bool DecrementOldEntry(unsigned CPI
, MachineInstr
* CPEMI
);
147 int LookForExistingCPEntry(CPUser
& U
, unsigned UserOffset
);
148 bool LookForWater(CPUser
&U
, unsigned UserOffset
,
149 MachineBasicBlock
** NewMBB
);
150 MachineBasicBlock
* AcceptWater(MachineBasicBlock
*WaterBB
,
151 std::vector
<MachineBasicBlock
*>::iterator IP
);
152 void CreateNewWater(unsigned CPUserIndex
, unsigned UserOffset
,
153 MachineBasicBlock
** NewMBB
);
154 bool HandleConstantPoolUser(MachineFunction
&Fn
, unsigned CPUserIndex
);
155 void RemoveDeadCPEMI(MachineInstr
*CPEMI
);
156 bool RemoveUnusedCPEntries();
157 bool CPEIsInRange(MachineInstr
*MI
, unsigned UserOffset
,
158 MachineInstr
*CPEMI
, unsigned Disp
,
160 bool WaterIsInRange(unsigned UserOffset
, MachineBasicBlock
*Water
,
162 bool OffsetIsInRange(unsigned UserOffset
, unsigned TrialOffset
,
163 unsigned Disp
, bool NegativeOK
);
164 bool BBIsInRange(MachineInstr
*MI
, MachineBasicBlock
*BB
, unsigned Disp
);
165 bool FixUpImmediateBr(MachineFunction
&Fn
, ImmBranch
&Br
);
166 bool FixUpConditionalBr(MachineFunction
&Fn
, ImmBranch
&Br
);
167 bool FixUpUnconditionalBr(MachineFunction
&Fn
, ImmBranch
&Br
);
168 bool UndoLRSpillRestore();
170 unsigned GetOffsetOf(MachineInstr
*MI
) const;
172 void verify(MachineFunction
&Fn
);
174 char ARMConstantIslands::ID
= 0;
177 /// verify - check BBOffsets, BBSizes, alignment of islands
178 void ARMConstantIslands::verify(MachineFunction
&Fn
) {
179 assert(BBOffsets
.size() == BBSizes
.size());
180 for (unsigned i
= 1, e
= BBOffsets
.size(); i
!= e
; ++i
)
181 assert(BBOffsets
[i
-1]+BBSizes
[i
-1] == BBOffsets
[i
]);
183 for (MachineFunction::iterator MBBI
= Fn
.begin(), E
= Fn
.end();
185 MachineBasicBlock
*MBB
= MBBI
;
187 MBB
->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY
)
188 assert((BBOffsets
[MBB
->getNumber()]%4 == 0 &&
189 BBSizes
[MBB
->getNumber()]%4 == 0) ||
190 (BBOffsets
[MBB
->getNumber()]%4 != 0 &&
191 BBSizes
[MBB
->getNumber()]%4 != 0));
196 /// print block size and offset information - debugging
197 void ARMConstantIslands::dumpBBs() {
198 for (unsigned J
= 0, E
= BBOffsets
.size(); J
!=E
; ++J
) {
199 DOUT
<< "block " << J
<< " offset " << BBOffsets
[J
] <<
200 " size " << BBSizes
[J
] << "\n";
204 /// createARMConstantIslandPass - returns an instance of the constpool
206 FunctionPass
*llvm::createARMConstantIslandPass() {
207 return new ARMConstantIslands();
210 bool ARMConstantIslands::runOnMachineFunction(MachineFunction
&Fn
) {
211 MachineConstantPool
&MCP
= *Fn
.getConstantPool();
213 TII
= Fn
.getTarget().getInstrInfo();
214 AFI
= Fn
.getInfo
<ARMFunctionInfo
>();
215 isThumb
= AFI
->isThumbFunction();
219 // Renumber all of the machine basic blocks in the function, guaranteeing that
220 // the numbers agree with the position of the block in the function.
223 /// Thumb functions containing constant pools get 2-byte alignment.
224 /// This is so we can keep exact track of where the alignment padding goes.
226 AFI
->setAlign(isThumb
? 1U : 2U);
228 // Perform the initial placement of the constant pool entries. To start with,
229 // we put them all at the end of the function.
230 std::vector
<MachineInstr
*> CPEMIs
;
231 if (!MCP
.isEmpty()) {
232 DoInitialPlacement(Fn
, CPEMIs
);
237 /// The next UID to take is the first unused one.
238 AFI
->initConstPoolEntryUId(CPEMIs
.size());
240 // Do the initial scan of the function, building up information about the
241 // sizes of each block, the location of all the water, and finding all of the
242 // constant pool users.
243 InitialFunctionScan(Fn
, CPEMIs
);
246 /// Remove dead constant pool entries.
247 RemoveUnusedCPEntries();
249 // Iteratively place constant pool entries and fix up branches until there
251 bool MadeChange
= false;
254 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
)
255 Change
|= HandleConstantPoolUser(Fn
, i
);
257 for (unsigned i
= 0, e
= ImmBranches
.size(); i
!= e
; ++i
)
258 Change
|= FixUpImmediateBr(Fn
, ImmBranches
[i
]);
265 // After a while, this might be made debug-only, but it is not expensive.
268 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
269 // Undo the spill / restore of LR if possible.
270 if (!HasFarJump
&& AFI
->isLRSpilledForFarJump() && isThumb
)
271 MadeChange
|= UndoLRSpillRestore();
284 /// DoInitialPlacement - Perform the initial placement of the constant pool
285 /// entries. To start with, we put them all at the end of the function.
286 void ARMConstantIslands::DoInitialPlacement(MachineFunction
&Fn
,
287 std::vector
<MachineInstr
*> &CPEMIs
) {
288 // Create the basic block to hold the CPE's.
289 MachineBasicBlock
*BB
= Fn
.CreateMachineBasicBlock();
292 // Add all of the constants from the constant pool to the end block, use an
293 // identity mapping of CPI's to CPE's.
294 const std::vector
<MachineConstantPoolEntry
> &CPs
=
295 Fn
.getConstantPool()->getConstants();
297 const TargetData
&TD
= *Fn
.getTarget().getTargetData();
298 for (unsigned i
= 0, e
= CPs
.size(); i
!= e
; ++i
) {
299 unsigned Size
= TD
.getTypeAllocSize(CPs
[i
].getType());
300 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
301 // we would have to pad them out or something so that instructions stay
303 assert((Size
& 3) == 0 && "CP Entry not multiple of 4 bytes!");
304 MachineInstr
*CPEMI
=
305 BuildMI(BB
, DebugLoc::getUnknownLoc(), TII
->get(ARM::CONSTPOOL_ENTRY
))
306 .addImm(i
).addConstantPoolIndex(i
).addImm(Size
);
307 CPEMIs
.push_back(CPEMI
);
309 // Add a new CPEntry, but no corresponding CPUser yet.
310 std::vector
<CPEntry
> CPEs
;
311 CPEs
.push_back(CPEntry(CPEMI
, i
));
312 CPEntries
.push_back(CPEs
);
314 DOUT
<< "Moved CPI#" << i
<< " to end of function as #" << i
<< "\n";
318 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
319 /// into the block immediately after it.
320 static bool BBHasFallthrough(MachineBasicBlock
*MBB
) {
321 // Get the next machine basic block in the function.
322 MachineFunction::iterator MBBI
= MBB
;
323 if (next(MBBI
) == MBB
->getParent()->end()) // Can't fall off end of function.
326 MachineBasicBlock
*NextBB
= next(MBBI
);
327 for (MachineBasicBlock::succ_iterator I
= MBB
->succ_begin(),
328 E
= MBB
->succ_end(); I
!= E
; ++I
)
335 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
336 /// look up the corresponding CPEntry.
337 ARMConstantIslands::CPEntry
338 *ARMConstantIslands::findConstPoolEntry(unsigned CPI
,
339 const MachineInstr
*CPEMI
) {
340 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
341 // Number of entries per constpool index should be small, just do a
343 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
344 if (CPEs
[i
].CPEMI
== CPEMI
)
350 /// InitialFunctionScan - Do the initial scan of the function, building up
351 /// information about the sizes of each block, the location of all the water,
352 /// and finding all of the constant pool users.
353 void ARMConstantIslands::InitialFunctionScan(MachineFunction
&Fn
,
354 const std::vector
<MachineInstr
*> &CPEMIs
) {
356 for (MachineFunction::iterator MBBI
= Fn
.begin(), E
= Fn
.end();
358 MachineBasicBlock
&MBB
= *MBBI
;
360 // If this block doesn't fall through into the next MBB, then this is
361 // 'water' that a constant pool island could be placed.
362 if (!BBHasFallthrough(&MBB
))
363 WaterList
.push_back(&MBB
);
365 unsigned MBBSize
= 0;
366 for (MachineBasicBlock::iterator I
= MBB
.begin(), E
= MBB
.end();
368 // Add instruction size to MBBSize.
369 MBBSize
+= TII
->GetInstSizeInBytes(I
);
371 int Opc
= I
->getOpcode();
372 if (I
->getDesc().isBranch()) {
379 // A Thumb table jump may involve padding; for the offsets to
380 // be right, functions containing these must be 4-byte aligned.
382 if ((Offset
+MBBSize
)%4 != 0)
383 MBBSize
+= 2; // padding
384 continue; // Does not get an entry in ImmBranches
386 continue; // Ignore other JT branches
407 // Record this immediate branch.
408 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
409 ImmBranches
.push_back(ImmBranch(I
, MaxOffs
, isCond
, UOpc
));
412 if (Opc
== ARM::tPUSH
|| Opc
== ARM::tPOP_RET
)
413 PushPopMIs
.push_back(I
);
415 // Scan the instructions for constant pool operands.
416 for (unsigned op
= 0, e
= I
->getNumOperands(); op
!= e
; ++op
)
417 if (I
->getOperand(op
).isCPI()) {
418 // We found one. The addressing mode tells us the max displacement
419 // from the PC that this instruction permits.
421 // Basic size info comes from the TSFlags field.
424 unsigned TSFlags
= I
->getDesc().TSFlags
;
425 switch (TSFlags
& ARMII::AddrModeMask
) {
427 // Constant pool entries can reach anything.
428 if (I
->getOpcode() == ARM::CONSTPOOL_ENTRY
)
430 if (I
->getOpcode() == ARM::tLEApcrel
) {
431 Bits
= 8; // Taking the address of a CP entry.
434 assert(0 && "Unknown addressing mode for CP reference!");
435 case ARMII::AddrMode1
: // AM1: 8 bits << 2
437 Scale
= 4; // Taking the address of a CP entry.
439 case ARMII::AddrMode2
:
440 Bits
= 12; // +-offset_12
442 case ARMII::AddrMode3
:
443 Bits
= 8; // +-offset_8
445 // addrmode4 has no immediate offset.
446 case ARMII::AddrMode5
:
448 Scale
= 4; // +-(offset_8*4)
450 case ARMII::AddrModeT1
:
451 Bits
= 5; // +offset_5
453 case ARMII::AddrModeT2
:
455 Scale
= 2; // +(offset_5*2)
457 case ARMII::AddrModeT4
:
459 Scale
= 4; // +(offset_5*4)
461 case ARMII::AddrModeTs
:
463 Scale
= 4; // +(offset_8*4)
467 // Remember that this is a user of a CP entry.
468 unsigned CPI
= I
->getOperand(op
).getIndex();
469 MachineInstr
*CPEMI
= CPEMIs
[CPI
];
470 unsigned MaxOffs
= ((1 << Bits
)-1) * Scale
;
471 CPUsers
.push_back(CPUser(I
, CPEMI
, MaxOffs
));
473 // Increment corresponding CPEntry reference count.
474 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
475 assert(CPE
&& "Cannot find a corresponding CPEntry!");
478 // Instructions can only use one CP entry, don't bother scanning the
479 // rest of the operands.
484 // In thumb mode, if this block is a constpool island, we may need padding
485 // so it's aligned on 4 byte boundary.
488 MBB
.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY
&&
492 BBSizes
.push_back(MBBSize
);
493 BBOffsets
.push_back(Offset
);
498 /// GetOffsetOf - Return the current offset of the specified machine instruction
499 /// from the start of the function. This offset changes as stuff is moved
500 /// around inside the function.
501 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr
*MI
) const {
502 MachineBasicBlock
*MBB
= MI
->getParent();
504 // The offset is composed of two things: the sum of the sizes of all MBB's
505 // before this instruction's block, and the offset from the start of the block
507 unsigned Offset
= BBOffsets
[MBB
->getNumber()];
509 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
510 // alignment padding, and compensate if so.
512 MI
->getOpcode() == ARM::CONSTPOOL_ENTRY
&&
516 // Sum instructions before MI in MBB.
517 for (MachineBasicBlock::iterator I
= MBB
->begin(); ; ++I
) {
518 assert(I
!= MBB
->end() && "Didn't find MI in its own basic block?");
519 if (&*I
== MI
) return Offset
;
520 Offset
+= TII
->GetInstSizeInBytes(I
);
524 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
526 static bool CompareMBBNumbers(const MachineBasicBlock
*LHS
,
527 const MachineBasicBlock
*RHS
) {
528 return LHS
->getNumber() < RHS
->getNumber();
531 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
532 /// machine function, it upsets all of the block numbers. Renumber the blocks
533 /// and update the arrays that parallel this numbering.
534 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock
*NewBB
) {
535 // Renumber the MBB's to keep them consequtive.
536 NewBB
->getParent()->RenumberBlocks(NewBB
);
538 // Insert a size into BBSizes to align it properly with the (newly
539 // renumbered) block numbers.
540 BBSizes
.insert(BBSizes
.begin()+NewBB
->getNumber(), 0);
542 // Likewise for BBOffsets.
543 BBOffsets
.insert(BBOffsets
.begin()+NewBB
->getNumber(), 0);
545 // Next, update WaterList. Specifically, we need to add NewMBB as having
546 // available water after it.
547 std::vector
<MachineBasicBlock
*>::iterator IP
=
548 std::lower_bound(WaterList
.begin(), WaterList
.end(), NewBB
,
550 WaterList
.insert(IP
, NewBB
);
554 /// Split the basic block containing MI into two blocks, which are joined by
555 /// an unconditional branch. Update datastructures and renumber blocks to
556 /// account for this change and returns the newly created block.
557 MachineBasicBlock
*ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr
*MI
) {
558 MachineBasicBlock
*OrigBB
= MI
->getParent();
559 MachineFunction
&MF
= *OrigBB
->getParent();
561 // Create a new MBB for the code after the OrigBB.
562 MachineBasicBlock
*NewBB
=
563 MF
.CreateMachineBasicBlock(OrigBB
->getBasicBlock());
564 MachineFunction::iterator MBBI
= OrigBB
; ++MBBI
;
565 MF
.insert(MBBI
, NewBB
);
567 // Splice the instructions starting with MI over to NewBB.
568 NewBB
->splice(NewBB
->end(), OrigBB
, MI
, OrigBB
->end());
570 // Add an unconditional branch from OrigBB to NewBB.
571 // Note the new unconditional branch is not being recorded.
572 // There doesn't seem to be meaningful DebugInfo available; this doesn't
573 // correspond to anything in the source.
574 BuildMI(OrigBB
, DebugLoc::getUnknownLoc(),
575 TII
->get(isThumb
? ARM::tB
: ARM::B
)).addMBB(NewBB
);
578 // Update the CFG. All succs of OrigBB are now succs of NewBB.
579 while (!OrigBB
->succ_empty()) {
580 MachineBasicBlock
*Succ
= *OrigBB
->succ_begin();
581 OrigBB
->removeSuccessor(Succ
);
582 NewBB
->addSuccessor(Succ
);
584 // This pass should be run after register allocation, so there should be no
585 // PHI nodes to update.
586 assert((Succ
->empty() || Succ
->begin()->getOpcode() != TargetInstrInfo::PHI
)
587 && "PHI nodes should be eliminated by now!");
590 // OrigBB branches to NewBB.
591 OrigBB
->addSuccessor(NewBB
);
593 // Update internal data structures to account for the newly inserted MBB.
594 // This is almost the same as UpdateForInsertedWaterBlock, except that
595 // the Water goes after OrigBB, not NewBB.
596 MF
.RenumberBlocks(NewBB
);
598 // Insert a size into BBSizes to align it properly with the (newly
599 // renumbered) block numbers.
600 BBSizes
.insert(BBSizes
.begin()+NewBB
->getNumber(), 0);
602 // Likewise for BBOffsets.
603 BBOffsets
.insert(BBOffsets
.begin()+NewBB
->getNumber(), 0);
605 // Next, update WaterList. Specifically, we need to add OrigMBB as having
606 // available water after it (but not if it's already there, which happens
607 // when splitting before a conditional branch that is followed by an
608 // unconditional branch - in that case we want to insert NewBB).
609 std::vector
<MachineBasicBlock
*>::iterator IP
=
610 std::lower_bound(WaterList
.begin(), WaterList
.end(), OrigBB
,
612 MachineBasicBlock
* WaterBB
= *IP
;
613 if (WaterBB
== OrigBB
)
614 WaterList
.insert(next(IP
), NewBB
);
616 WaterList
.insert(IP
, OrigBB
);
618 // Figure out how large the first NewMBB is. (It cannot
619 // contain a constpool_entry or tablejump.)
620 unsigned NewBBSize
= 0;
621 for (MachineBasicBlock::iterator I
= NewBB
->begin(), E
= NewBB
->end();
623 NewBBSize
+= TII
->GetInstSizeInBytes(I
);
625 unsigned OrigBBI
= OrigBB
->getNumber();
626 unsigned NewBBI
= NewBB
->getNumber();
627 // Set the size of NewBB in BBSizes.
628 BBSizes
[NewBBI
] = NewBBSize
;
630 // We removed instructions from UserMBB, subtract that off from its size.
631 // Add 2 or 4 to the block to count the unconditional branch we added to it.
632 unsigned delta
= isThumb
? 2 : 4;
633 BBSizes
[OrigBBI
] -= NewBBSize
- delta
;
635 // ...and adjust BBOffsets for NewBB accordingly.
636 BBOffsets
[NewBBI
] = BBOffsets
[OrigBBI
] + BBSizes
[OrigBBI
];
638 // All BBOffsets following these blocks must be modified.
639 AdjustBBOffsetsAfter(NewBB
, delta
);
644 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
645 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
646 /// constant pool entry).
647 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset
,
648 unsigned TrialOffset
, unsigned MaxDisp
, bool NegativeOK
) {
649 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
650 // purposes of the displacement computation; compensate for that here.
651 // Effectively, the valid range of displacements is 2 bytes smaller for such
653 if (isThumb
&& UserOffset
%4 !=0)
655 // CPEs will be rounded up to a multiple of 4.
656 if (isThumb
&& TrialOffset
%4 != 0)
659 if (UserOffset
<= TrialOffset
) {
660 // User before the Trial.
661 if (TrialOffset
-UserOffset
<= MaxDisp
)
663 } else if (NegativeOK
) {
664 if (UserOffset
-TrialOffset
<= MaxDisp
)
670 /// WaterIsInRange - Returns true if a CPE placed after the specified
671 /// Water (a basic block) will be in range for the specific MI.
673 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset
,
674 MachineBasicBlock
* Water
, CPUser
&U
)
676 unsigned MaxDisp
= U
.MaxDisp
;
677 MachineFunction::iterator I
= next(MachineFunction::iterator(Water
));
678 unsigned CPEOffset
= BBOffsets
[Water
->getNumber()] +
679 BBSizes
[Water
->getNumber()];
681 // If the CPE is to be inserted before the instruction, that will raise
682 // the offset of the instruction. (Currently applies only to ARM, so
683 // no alignment compensation attempted here.)
684 if (CPEOffset
< UserOffset
)
685 UserOffset
+= U
.CPEMI
->getOperand(2).getImm();
687 return OffsetIsInRange (UserOffset
, CPEOffset
, MaxDisp
, !isThumb
);
690 /// CPEIsInRange - Returns true if the distance between specific MI and
691 /// specific ConstPool entry instruction can fit in MI's displacement field.
692 bool ARMConstantIslands::CPEIsInRange(MachineInstr
*MI
, unsigned UserOffset
,
694 unsigned MaxDisp
, bool DoDump
) {
695 unsigned CPEOffset
= GetOffsetOf(CPEMI
);
696 assert(CPEOffset
%4 == 0 && "Misaligned CPE");
699 DOUT
<< "User of CPE#" << CPEMI
->getOperand(0).getImm()
700 << " max delta=" << MaxDisp
701 << " insn address=" << UserOffset
702 << " CPE address=" << CPEOffset
703 << " offset=" << int(CPEOffset
-UserOffset
) << "\t" << *MI
;
706 return OffsetIsInRange(UserOffset
, CPEOffset
, MaxDisp
, !isThumb
);
710 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
711 /// unconditionally branches to its only successor.
712 static bool BBIsJumpedOver(MachineBasicBlock
*MBB
) {
713 if (MBB
->pred_size() != 1 || MBB
->succ_size() != 1)
716 MachineBasicBlock
*Succ
= *MBB
->succ_begin();
717 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
718 MachineInstr
*PredMI
= &Pred
->back();
719 if (PredMI
->getOpcode() == ARM::B
|| PredMI
->getOpcode() == ARM::tB
)
720 return PredMI
->getOperand(0).getMBB() == Succ
;
725 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock
*BB
,
727 MachineFunction::iterator MBBI
= BB
; MBBI
= next(MBBI
);
728 for(unsigned i
=BB
->getNumber()+1; i
<BB
->getParent()->getNumBlockIDs(); i
++) {
729 BBOffsets
[i
] += delta
;
730 // If some existing blocks have padding, adjust the padding as needed, a
731 // bit tricky. delta can be negative so don't use % on that.
733 MachineBasicBlock
*MBB
= MBBI
;
735 // Constant pool entries require padding.
736 if (MBB
->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY
) {
737 unsigned oldOffset
= BBOffsets
[i
] - delta
;
738 if (oldOffset
%4==0 && BBOffsets
[i
]%4!=0) {
742 } else if (oldOffset
%4!=0 && BBOffsets
[i
]%4==0) {
743 // remove existing padding
748 // Thumb jump tables require padding. They should be at the end;
749 // following unconditional branches are removed by AnalyzeBranch.
750 MachineInstr
*ThumbJTMI
= NULL
;
751 if (prior(MBB
->end())->getOpcode() == ARM::tBR_JTr
)
752 ThumbJTMI
= prior(MBB
->end());
754 unsigned newMIOffset
= GetOffsetOf(ThumbJTMI
);
755 unsigned oldMIOffset
= newMIOffset
- delta
;
756 if (oldMIOffset
%4 == 0 && newMIOffset
%4 != 0) {
757 // remove existing padding
760 } else if (oldMIOffset
%4 != 0 && newMIOffset
%4 == 0) {
774 /// DecrementOldEntry - find the constant pool entry with index CPI
775 /// and instruction CPEMI, and decrement its refcount. If the refcount
776 /// becomes 0 remove the entry and instruction. Returns true if we removed
777 /// the entry, false if we didn't.
779 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI
, MachineInstr
*CPEMI
) {
780 // Find the old entry. Eliminate it if it is no longer used.
781 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
782 assert(CPE
&& "Unexpected!");
783 if (--CPE
->RefCount
== 0) {
784 RemoveDeadCPEMI(CPEMI
);
792 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
793 /// if not, see if an in-range clone of the CPE is in range, and if so,
794 /// change the data structures so the user references the clone. Returns:
795 /// 0 = no existing entry found
796 /// 1 = entry found, and there were no code insertions or deletions
797 /// 2 = entry found, and there were code insertions or deletions
798 int ARMConstantIslands::LookForExistingCPEntry(CPUser
& U
, unsigned UserOffset
)
800 MachineInstr
*UserMI
= U
.MI
;
801 MachineInstr
*CPEMI
= U
.CPEMI
;
803 // Check to see if the CPE is already in-range.
804 if (CPEIsInRange(UserMI
, UserOffset
, CPEMI
, U
.MaxDisp
, true)) {
805 DOUT
<< "In range\n";
809 // No. Look for previously created clones of the CPE that are in range.
810 unsigned CPI
= CPEMI
->getOperand(1).getIndex();
811 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
812 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
813 // We already tried this one
814 if (CPEs
[i
].CPEMI
== CPEMI
)
816 // Removing CPEs can leave empty entries, skip
817 if (CPEs
[i
].CPEMI
== NULL
)
819 if (CPEIsInRange(UserMI
, UserOffset
, CPEs
[i
].CPEMI
, U
.MaxDisp
, false)) {
820 DOUT
<< "Replacing CPE#" << CPI
<< " with CPE#" << CPEs
[i
].CPI
<< "\n";
821 // Point the CPUser node to the replacement
822 U
.CPEMI
= CPEs
[i
].CPEMI
;
823 // Change the CPI in the instruction operand to refer to the clone.
824 for (unsigned j
= 0, e
= UserMI
->getNumOperands(); j
!= e
; ++j
)
825 if (UserMI
->getOperand(j
).isCPI()) {
826 UserMI
->getOperand(j
).setIndex(CPEs
[i
].CPI
);
829 // Adjust the refcount of the clone...
831 // ...and the original. If we didn't remove the old entry, none of the
832 // addresses changed, so we don't need another pass.
833 return DecrementOldEntry(CPI
, CPEMI
) ? 2 : 1;
839 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
840 /// the specific unconditional branch instruction.
841 static inline unsigned getUnconditionalBrDisp(int Opc
) {
842 return (Opc
== ARM::tB
) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
845 /// AcceptWater - Small amount of common code factored out of the following.
847 MachineBasicBlock
* ARMConstantIslands::AcceptWater(MachineBasicBlock
*WaterBB
,
848 std::vector
<MachineBasicBlock
*>::iterator IP
) {
849 DOUT
<< "found water in range\n";
850 // Remove the original WaterList entry; we want subsequent
851 // insertions in this vicinity to go after the one we're
852 // about to insert. This considerably reduces the number
853 // of times we have to move the same CPE more than once.
855 // CPE goes before following block (NewMBB).
856 return next(MachineFunction::iterator(WaterBB
));
859 /// LookForWater - look for an existing entry in the WaterList in which
860 /// we can place the CPE referenced from U so it's within range of U's MI.
861 /// Returns true if found, false if not. If it returns true, *NewMBB
862 /// is set to the WaterList entry.
863 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
864 /// water that will not introduce padding to water that will; within each
865 /// group, prefer the water that's farthest away.
867 bool ARMConstantIslands::LookForWater(CPUser
&U
, unsigned UserOffset
,
868 MachineBasicBlock
** NewMBB
) {
869 std::vector
<MachineBasicBlock
*>::iterator IPThatWouldPad
;
870 MachineBasicBlock
* WaterBBThatWouldPad
= NULL
;
871 if (!WaterList
.empty()) {
872 for (std::vector
<MachineBasicBlock
*>::iterator IP
= prior(WaterList
.end()),
873 B
= WaterList
.begin();; --IP
) {
874 MachineBasicBlock
* WaterBB
= *IP
;
875 if (WaterIsInRange(UserOffset
, WaterBB
, U
)) {
877 (BBOffsets
[WaterBB
->getNumber()] +
878 BBSizes
[WaterBB
->getNumber()])%4 != 0) {
879 // This is valid Water, but would introduce padding. Remember
880 // it in case we don't find any Water that doesn't do this.
881 if (!WaterBBThatWouldPad
) {
882 WaterBBThatWouldPad
= WaterBB
;
886 *NewMBB
= AcceptWater(WaterBB
, IP
);
894 if (isThumb
&& WaterBBThatWouldPad
) {
895 *NewMBB
= AcceptWater(WaterBBThatWouldPad
, IPThatWouldPad
);
901 /// CreateNewWater - No existing WaterList entry will work for
902 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
903 /// block is used if in range, and the conditional branch munged so control
904 /// flow is correct. Otherwise the block is split to create a hole with an
905 /// unconditional branch around it. In either case *NewMBB is set to a
906 /// block following which the new island can be inserted (the WaterList
907 /// is not adjusted).
909 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex
,
910 unsigned UserOffset
, MachineBasicBlock
** NewMBB
) {
911 CPUser
&U
= CPUsers
[CPUserIndex
];
912 MachineInstr
*UserMI
= U
.MI
;
913 MachineInstr
*CPEMI
= U
.CPEMI
;
914 MachineBasicBlock
*UserMBB
= UserMI
->getParent();
915 unsigned OffsetOfNextBlock
= BBOffsets
[UserMBB
->getNumber()] +
916 BBSizes
[UserMBB
->getNumber()];
917 assert(OffsetOfNextBlock
== BBOffsets
[UserMBB
->getNumber()+1]);
919 // If the use is at the end of the block, or the end of the block
920 // is within range, make new water there. (The addition below is
921 // for the unconditional branch we will be adding: 4 bytes on ARM,
922 // 2 on Thumb. Possible Thumb alignment padding is allowed for
923 // inside OffsetIsInRange.
924 // If the block ends in an unconditional branch already, it is water,
925 // and is known to be out of range, so we'll always be adding a branch.)
926 if (&UserMBB
->back() == UserMI
||
927 OffsetIsInRange(UserOffset
, OffsetOfNextBlock
+ (isThumb
? 2: 4),
928 U
.MaxDisp
, !isThumb
)) {
929 DOUT
<< "Split at end of block\n";
930 if (&UserMBB
->back() == UserMI
)
931 assert(BBHasFallthrough(UserMBB
) && "Expected a fallthrough BB!");
932 *NewMBB
= next(MachineFunction::iterator(UserMBB
));
933 // Add an unconditional branch from UserMBB to fallthrough block.
934 // Record it for branch lengthening; this new branch will not get out of
935 // range, but if the preceding conditional branch is out of range, the
936 // targets will be exchanged, and the altered branch may be out of
937 // range, so the machinery has to know about it.
938 int UncondBr
= isThumb
? ARM::tB
: ARM::B
;
939 BuildMI(UserMBB
, DebugLoc::getUnknownLoc(),
940 TII
->get(UncondBr
)).addMBB(*NewMBB
);
941 unsigned MaxDisp
= getUnconditionalBrDisp(UncondBr
);
942 ImmBranches
.push_back(ImmBranch(&UserMBB
->back(),
943 MaxDisp
, false, UncondBr
));
944 int delta
= isThumb
? 2 : 4;
945 BBSizes
[UserMBB
->getNumber()] += delta
;
946 AdjustBBOffsetsAfter(UserMBB
, delta
);
948 // What a big block. Find a place within the block to split it.
949 // This is a little tricky on Thumb since instructions are 2 bytes
950 // and constant pool entries are 4 bytes: if instruction I references
951 // island CPE, and instruction I+1 references CPE', it will
952 // not work well to put CPE as far forward as possible, since then
953 // CPE' cannot immediately follow it (that location is 2 bytes
954 // farther away from I+1 than CPE was from I) and we'd need to create
955 // a new island. So, we make a first guess, then walk through the
956 // instructions between the one currently being looked at and the
957 // possible insertion point, and make sure any other instructions
958 // that reference CPEs will be able to use the same island area;
959 // if not, we back up the insertion point.
961 // The 4 in the following is for the unconditional branch we'll be
962 // inserting (allows for long branch on Thumb). Alignment of the
963 // island is handled inside OffsetIsInRange.
964 unsigned BaseInsertOffset
= UserOffset
+ U
.MaxDisp
-4;
965 // This could point off the end of the block if we've already got
966 // constant pool entries following this block; only the last one is
967 // in the water list. Back past any possible branches (allow for a
968 // conditional and a maximally long unconditional).
969 if (BaseInsertOffset
>= BBOffsets
[UserMBB
->getNumber()+1])
970 BaseInsertOffset
= BBOffsets
[UserMBB
->getNumber()+1] -
972 unsigned EndInsertOffset
= BaseInsertOffset
+
973 CPEMI
->getOperand(2).getImm();
974 MachineBasicBlock::iterator MI
= UserMI
;
976 unsigned CPUIndex
= CPUserIndex
+1;
977 for (unsigned Offset
= UserOffset
+TII
->GetInstSizeInBytes(UserMI
);
978 Offset
< BaseInsertOffset
;
979 Offset
+= TII
->GetInstSizeInBytes(MI
),
981 if (CPUIndex
< CPUsers
.size() && CPUsers
[CPUIndex
].MI
== MI
) {
982 if (!OffsetIsInRange(Offset
, EndInsertOffset
,
983 CPUsers
[CPUIndex
].MaxDisp
, !isThumb
)) {
984 BaseInsertOffset
-= (isThumb
? 2 : 4);
985 EndInsertOffset
-= (isThumb
? 2 : 4);
987 // This is overly conservative, as we don't account for CPEMIs
988 // being reused within the block, but it doesn't matter much.
989 EndInsertOffset
+= CPUsers
[CPUIndex
].CPEMI
->getOperand(2).getImm();
993 DOUT
<< "Split in middle of big block\n";
994 *NewMBB
= SplitBlockBeforeInstr(prior(MI
));
998 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
999 /// is out-of-range. If so, pick up the constant pool value and move it some
1000 /// place in-range. Return true if we changed any addresses (thus must run
1001 /// another pass of branch lengthening), false otherwise.
1002 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction
&Fn
,
1003 unsigned CPUserIndex
) {
1004 CPUser
&U
= CPUsers
[CPUserIndex
];
1005 MachineInstr
*UserMI
= U
.MI
;
1006 MachineInstr
*CPEMI
= U
.CPEMI
;
1007 unsigned CPI
= CPEMI
->getOperand(1).getIndex();
1008 unsigned Size
= CPEMI
->getOperand(2).getImm();
1009 MachineBasicBlock
*NewMBB
;
1010 // Compute this only once, it's expensive. The 4 or 8 is the value the
1011 // hardware keeps in the PC (2 insns ahead of the reference).
1012 unsigned UserOffset
= GetOffsetOf(UserMI
) + (isThumb
? 4 : 8);
1014 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1015 // second instruction.
1016 if (UserMI
->getOpcode() == ARM::tLEApcrel
)
1019 // See if the current entry is within range, or there is a clone of it
1021 int result
= LookForExistingCPEntry(U
, UserOffset
);
1022 if (result
==1) return false;
1023 else if (result
==2) return true;
1025 // No existing clone of this CPE is within range.
1026 // We will be generating a new clone. Get a UID for it.
1027 unsigned ID
= AFI
->createConstPoolEntryUId();
1029 // Look for water where we can place this CPE. We look for the farthest one
1030 // away that will work. Forward references only for now (although later
1031 // we might find some that are backwards).
1033 if (!LookForWater(U
, UserOffset
, &NewMBB
)) {
1035 DOUT
<< "No water found\n";
1036 CreateNewWater(CPUserIndex
, UserOffset
, &NewMBB
);
1039 // Okay, we know we can put an island before NewMBB now, do it!
1040 MachineBasicBlock
*NewIsland
= Fn
.CreateMachineBasicBlock();
1041 Fn
.insert(NewMBB
, NewIsland
);
1043 // Update internal data structures to account for the newly inserted MBB.
1044 UpdateForInsertedWaterBlock(NewIsland
);
1046 // Decrement the old entry, and remove it if refcount becomes 0.
1047 DecrementOldEntry(CPI
, CPEMI
);
1049 // Now that we have an island to add the CPE to, clone the original CPE and
1050 // add it to the island.
1051 U
.CPEMI
= BuildMI(NewIsland
, DebugLoc::getUnknownLoc(),
1052 TII
->get(ARM::CONSTPOOL_ENTRY
))
1053 .addImm(ID
).addConstantPoolIndex(CPI
).addImm(Size
);
1054 CPEntries
[CPI
].push_back(CPEntry(U
.CPEMI
, ID
, 1));
1057 BBOffsets
[NewIsland
->getNumber()] = BBOffsets
[NewMBB
->getNumber()];
1058 // Compensate for .align 2 in thumb mode.
1059 if (isThumb
&& BBOffsets
[NewIsland
->getNumber()]%4 != 0)
1061 // Increase the size of the island block to account for the new entry.
1062 BBSizes
[NewIsland
->getNumber()] += Size
;
1063 AdjustBBOffsetsAfter(NewIsland
, Size
);
1065 // Finally, change the CPI in the instruction operand to be ID.
1066 for (unsigned i
= 0, e
= UserMI
->getNumOperands(); i
!= e
; ++i
)
1067 if (UserMI
->getOperand(i
).isCPI()) {
1068 UserMI
->getOperand(i
).setIndex(ID
);
1072 DOUT
<< " Moved CPE to #" << ID
<< " CPI=" << CPI
<< "\t" << *UserMI
;
1077 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1078 /// sizes and offsets of impacted basic blocks.
1079 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr
*CPEMI
) {
1080 MachineBasicBlock
*CPEBB
= CPEMI
->getParent();
1081 unsigned Size
= CPEMI
->getOperand(2).getImm();
1082 CPEMI
->eraseFromParent();
1083 BBSizes
[CPEBB
->getNumber()] -= Size
;
1084 // All succeeding offsets have the current size value added in, fix this.
1085 if (CPEBB
->empty()) {
1086 // In thumb mode, the size of island may be padded by two to compensate for
1087 // the alignment requirement. Then it will now be 2 when the block is
1088 // empty, so fix this.
1089 // All succeeding offsets have the current size value added in, fix this.
1090 if (BBSizes
[CPEBB
->getNumber()] != 0) {
1091 Size
+= BBSizes
[CPEBB
->getNumber()];
1092 BBSizes
[CPEBB
->getNumber()] = 0;
1095 AdjustBBOffsetsAfter(CPEBB
, -Size
);
1096 // An island has only one predecessor BB and one successor BB. Check if
1097 // this BB's predecessor jumps directly to this BB's successor. This
1098 // shouldn't happen currently.
1099 assert(!BBIsJumpedOver(CPEBB
) && "How did this happen?");
1100 // FIXME: remove the empty blocks after all the work is done?
1103 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1105 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1106 unsigned MadeChange
= false;
1107 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
1108 std::vector
<CPEntry
> &CPEs
= CPEntries
[i
];
1109 for (unsigned j
= 0, ee
= CPEs
.size(); j
!= ee
; ++j
) {
1110 if (CPEs
[j
].RefCount
== 0 && CPEs
[j
].CPEMI
) {
1111 RemoveDeadCPEMI(CPEs
[j
].CPEMI
);
1112 CPEs
[j
].CPEMI
= NULL
;
1120 /// BBIsInRange - Returns true if the distance between specific MI and
1121 /// specific BB can fit in MI's displacement field.
1122 bool ARMConstantIslands::BBIsInRange(MachineInstr
*MI
,MachineBasicBlock
*DestBB
,
1124 unsigned PCAdj
= isThumb
? 4 : 8;
1125 unsigned BrOffset
= GetOffsetOf(MI
) + PCAdj
;
1126 unsigned DestOffset
= BBOffsets
[DestBB
->getNumber()];
1128 DOUT
<< "Branch of destination BB#" << DestBB
->getNumber()
1129 << " from BB#" << MI
->getParent()->getNumber()
1130 << " max delta=" << MaxDisp
1131 << " from " << GetOffsetOf(MI
) << " to " << DestOffset
1132 << " offset " << int(DestOffset
-BrOffset
) << "\t" << *MI
;
1134 if (BrOffset
<= DestOffset
) {
1135 // Branch before the Dest.
1136 if (DestOffset
-BrOffset
<= MaxDisp
)
1139 if (BrOffset
-DestOffset
<= MaxDisp
)
1145 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1146 /// away to fit in its displacement field.
1147 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction
&Fn
, ImmBranch
&Br
) {
1148 MachineInstr
*MI
= Br
.MI
;
1149 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1151 // Check to see if the DestBB is already in-range.
1152 if (BBIsInRange(MI
, DestBB
, Br
.MaxDisp
))
1156 return FixUpUnconditionalBr(Fn
, Br
);
1157 return FixUpConditionalBr(Fn
, Br
);
1160 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1161 /// too far away to fit in its displacement field. If the LR register has been
1162 /// spilled in the epilogue, then we can use BL to implement a far jump.
1163 /// Otherwise, add an intermediate branch instruction to a branch.
1165 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction
&Fn
, ImmBranch
&Br
) {
1166 MachineInstr
*MI
= Br
.MI
;
1167 MachineBasicBlock
*MBB
= MI
->getParent();
1168 assert(isThumb
&& "Expected a Thumb function!");
1170 // Use BL to implement far jump.
1171 Br
.MaxDisp
= (1 << 21) * 2;
1172 MI
->setDesc(TII
->get(ARM::tBfar
));
1173 BBSizes
[MBB
->getNumber()] += 2;
1174 AdjustBBOffsetsAfter(MBB
, 2);
1178 DOUT
<< " Changed B to long jump " << *MI
;
1183 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1184 /// far away to fit in its displacement field. It is converted to an inverse
1185 /// conditional branch + an unconditional branch to the destination.
1187 ARMConstantIslands::FixUpConditionalBr(MachineFunction
&Fn
, ImmBranch
&Br
) {
1188 MachineInstr
*MI
= Br
.MI
;
1189 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1191 // Add an unconditional branch to the destination and invert the branch
1192 // condition to jump over it:
1198 ARMCC::CondCodes CC
= (ARMCC::CondCodes
)MI
->getOperand(1).getImm();
1199 CC
= ARMCC::getOppositeCondition(CC
);
1200 unsigned CCReg
= MI
->getOperand(2).getReg();
1202 // If the branch is at the end of its MBB and that has a fall-through block,
1203 // direct the updated conditional branch to the fall-through block. Otherwise,
1204 // split the MBB before the next instruction.
1205 MachineBasicBlock
*MBB
= MI
->getParent();
1206 MachineInstr
*BMI
= &MBB
->back();
1207 bool NeedSplit
= (BMI
!= MI
) || !BBHasFallthrough(MBB
);
1211 if (next(MachineBasicBlock::iterator(MI
)) == prior(MBB
->end()) &&
1212 BMI
->getOpcode() == Br
.UncondBr
) {
1213 // Last MI in the BB is an unconditional branch. Can we simply invert the
1214 // condition and swap destinations:
1220 MachineBasicBlock
*NewDest
= BMI
->getOperand(0).getMBB();
1221 if (BBIsInRange(MI
, NewDest
, Br
.MaxDisp
)) {
1222 DOUT
<< " Invert Bcc condition and swap its destination with " << *BMI
;
1223 BMI
->getOperand(0).setMBB(DestBB
);
1224 MI
->getOperand(0).setMBB(NewDest
);
1225 MI
->getOperand(1).setImm(CC
);
1232 SplitBlockBeforeInstr(MI
);
1233 // No need for the branch to the next block. We're adding an unconditional
1234 // branch to the destination.
1235 int delta
= TII
->GetInstSizeInBytes(&MBB
->back());
1236 BBSizes
[MBB
->getNumber()] -= delta
;
1237 MachineBasicBlock
* SplitBB
= next(MachineFunction::iterator(MBB
));
1238 AdjustBBOffsetsAfter(SplitBB
, -delta
);
1239 MBB
->back().eraseFromParent();
1240 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1242 MachineBasicBlock
*NextBB
= next(MachineFunction::iterator(MBB
));
1244 DOUT
<< " Insert B to BB#" << DestBB
->getNumber()
1245 << " also invert condition and change dest. to BB#"
1246 << NextBB
->getNumber() << "\n";
1248 // Insert a new conditional branch and a new unconditional branch.
1249 // Also update the ImmBranch as well as adding a new entry for the new branch.
1250 BuildMI(MBB
, DebugLoc::getUnknownLoc(),
1251 TII
->get(MI
->getOpcode()))
1252 .addMBB(NextBB
).addImm(CC
).addReg(CCReg
);
1253 Br
.MI
= &MBB
->back();
1254 BBSizes
[MBB
->getNumber()] += TII
->GetInstSizeInBytes(&MBB
->back());
1255 BuildMI(MBB
, DebugLoc::getUnknownLoc(), TII
->get(Br
.UncondBr
)).addMBB(DestBB
);
1256 BBSizes
[MBB
->getNumber()] += TII
->GetInstSizeInBytes(&MBB
->back());
1257 unsigned MaxDisp
= getUnconditionalBrDisp(Br
.UncondBr
);
1258 ImmBranches
.push_back(ImmBranch(&MBB
->back(), MaxDisp
, false, Br
.UncondBr
));
1260 // Remove the old conditional branch. It may or may not still be in MBB.
1261 BBSizes
[MI
->getParent()->getNumber()] -= TII
->GetInstSizeInBytes(MI
);
1262 MI
->eraseFromParent();
1264 // The net size change is an addition of one unconditional branch.
1265 int delta
= TII
->GetInstSizeInBytes(&MBB
->back());
1266 AdjustBBOffsetsAfter(MBB
, delta
);
1270 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1271 /// LR / restores LR to pc.
1272 bool ARMConstantIslands::UndoLRSpillRestore() {
1273 bool MadeChange
= false;
1274 for (unsigned i
= 0, e
= PushPopMIs
.size(); i
!= e
; ++i
) {
1275 MachineInstr
*MI
= PushPopMIs
[i
];
1276 if (MI
->getOpcode() == ARM::tPOP_RET
&&
1277 MI
->getOperand(0).getReg() == ARM::PC
&&
1278 MI
->getNumExplicitOperands() == 1) {
1279 BuildMI(MI
->getParent(), MI
->getDebugLoc(), TII
->get(ARM::tBX_RET
));
1280 MI
->eraseFromParent();