1 //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains a pass that splits the constant pool up into 'islands'
10 // which are scattered through-out the function. This is required due to the
11 // limited pc-relative displacements that ARM has.
13 //===----------------------------------------------------------------------===//
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBasicBlockInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMBaseInfo.h"
21 #include "Thumb2InstrInfo.h"
22 #include "Utils/ARMBaseInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/CodeGen/LivePhysRegs.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Config/llvm-config.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/MC/MCInstrDesc.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
59 #define DEBUG_TYPE "arm-cp-islands"
61 #define ARM_CP_ISLANDS_OPT_NAME \
62 "ARM constant island placement and branch shortening pass"
63 STATISTIC(NumCPEs
, "Number of constpool entries");
64 STATISTIC(NumSplit
, "Number of uncond branches inserted");
65 STATISTIC(NumCBrFixed
, "Number of cond branches fixed");
66 STATISTIC(NumUBrFixed
, "Number of uncond branches fixed");
67 STATISTIC(NumTBs
, "Number of table branches generated");
68 STATISTIC(NumT2CPShrunk
, "Number of Thumb2 constantpool instructions shrunk");
69 STATISTIC(NumT2BrShrunk
, "Number of Thumb2 immediate branches shrunk");
70 STATISTIC(NumCBZ
, "Number of CBZ / CBNZ formed");
71 STATISTIC(NumJTMoved
, "Number of jump table destination blocks moved");
72 STATISTIC(NumJTInserted
, "Number of jump table intermediate blocks inserted");
75 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden
, cl::init(true),
76 cl::desc("Adjust basic block layout to better use TB[BH]"));
78 static cl::opt
<unsigned>
79 CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden
, cl::init(30),
80 cl::desc("The max number of iteration for converge"));
82 static cl::opt
<bool> SynthesizeThumb1TBB(
83 "arm-synthesize-thumb-1-tbb", cl::Hidden
, cl::init(true),
84 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
85 "equivalent to the TBB/TBH instructions"));
89 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
90 /// requires constant pool entries to be scattered among the instructions
91 /// inside a function. To do this, it completely ignores the normal LLVM
92 /// constant pool; instead, it places constants wherever it feels like with
93 /// special instructions.
95 /// The terminology used in this pass includes:
96 /// Islands - Clumps of constants placed in the function.
97 /// Water - Potential places where an island could be formed.
98 /// CPE - A constant pool entry that has been placed somewhere, which
99 /// tracks a list of users.
100 class ARMConstantIslands
: public MachineFunctionPass
{
101 std::unique_ptr
<ARMBasicBlockUtils
> BBUtils
= nullptr;
103 /// WaterList - A sorted list of basic blocks where islands could be placed
104 /// (i.e. blocks that don't fall through to the following block, due
105 /// to a return, unreachable, or unconditional branch).
106 std::vector
<MachineBasicBlock
*> WaterList
;
108 /// NewWaterList - The subset of WaterList that was created since the
109 /// previous iteration by inserting unconditional branches.
110 SmallSet
<MachineBasicBlock
*, 4> NewWaterList
;
112 using water_iterator
= std::vector
<MachineBasicBlock
*>::iterator
;
114 /// CPUser - One user of a constant pool, keeping the machine instruction
115 /// pointer, the constant pool being referenced, and the max displacement
116 /// allowed from the instruction to the CP. The HighWaterMark records the
117 /// highest basic block where a new CPEntry can be placed. To ensure this
118 /// pass terminates, the CP entries are initially placed at the end of the
119 /// function and then move monotonically to lower addresses. The
120 /// exception to this rule is when the current CP entry for a particular
121 /// CPUser is out of range, but there is another CP entry for the same
122 /// constant value in range. We want to use the existing in-range CP
123 /// entry, but if it later moves out of range, the search for new water
124 /// should resume where it left off. The HighWaterMark is used to record
129 MachineBasicBlock
*HighWaterMark
;
133 bool KnownAlignment
= false;
135 CPUser(MachineInstr
*mi
, MachineInstr
*cpemi
, unsigned maxdisp
,
136 bool neg
, bool soimm
)
137 : MI(mi
), CPEMI(cpemi
), MaxDisp(maxdisp
), NegOk(neg
), IsSoImm(soimm
) {
138 HighWaterMark
= CPEMI
->getParent();
141 /// getMaxDisp - Returns the maximum displacement supported by MI.
142 /// Correct for unknown alignment.
143 /// Conservatively subtract 2 bytes to handle weird alignment effects.
144 unsigned getMaxDisp() const {
145 return (KnownAlignment
? MaxDisp
: MaxDisp
- 2) - 2;
149 /// CPUsers - Keep track of all of the machine instructions that use various
150 /// constant pools and their max displacement.
151 std::vector
<CPUser
> CPUsers
;
153 /// CPEntry - One per constant pool entry, keeping the machine instruction
154 /// pointer, the constpool index, and the number of CPUser's which
155 /// reference this entry.
161 CPEntry(MachineInstr
*cpemi
, unsigned cpi
, unsigned rc
= 0)
162 : CPEMI(cpemi
), CPI(cpi
), RefCount(rc
) {}
165 /// CPEntries - Keep track of all of the constant pool entry machine
166 /// instructions. For each original constpool index (i.e. those that existed
167 /// upon entry to this pass), it keeps a vector of entries. Original
168 /// elements are cloned as we go along; the clones are put in the vector of
169 /// the original element, but have distinct CPIs.
171 /// The first half of CPEntries contains generic constants, the second half
172 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
173 /// which vector it will be in here.
174 std::vector
<std::vector
<CPEntry
>> CPEntries
;
176 /// Maps a JT index to the offset in CPEntries containing copies of that
177 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
178 DenseMap
<int, int> JumpTableEntryIndices
;
180 /// Maps a JT index to the LEA that actually uses the index to calculate its
182 DenseMap
<int, int> JumpTableUserIndices
;
184 /// ImmBranch - One per immediate branch, keeping the machine instruction
185 /// pointer, conditional or unconditional, the max displacement,
186 /// and (if isCond is true) the corresponding unconditional branch
190 unsigned MaxDisp
: 31;
194 ImmBranch(MachineInstr
*mi
, unsigned maxdisp
, bool cond
, unsigned ubr
)
195 : MI(mi
), MaxDisp(maxdisp
), isCond(cond
), UncondBr(ubr
) {}
198 /// ImmBranches - Keep track of all the immediate branch instructions.
199 std::vector
<ImmBranch
> ImmBranches
;
201 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
202 SmallVector
<MachineInstr
*, 4> PushPopMIs
;
204 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
205 SmallVector
<MachineInstr
*, 4> T2JumpTables
;
207 /// HasFarJump - True if any far jump instruction has been emitted during
208 /// the branch fix up pass.
212 MachineConstantPool
*MCP
;
213 const ARMBaseInstrInfo
*TII
;
214 const ARMSubtarget
*STI
;
215 ARMFunctionInfo
*AFI
;
219 bool isPositionIndependentOrROPI
;
224 ARMConstantIslands() : MachineFunctionPass(ID
) {}
226 bool runOnMachineFunction(MachineFunction
&MF
) override
;
228 MachineFunctionProperties
getRequiredProperties() const override
{
229 return MachineFunctionProperties().set(
230 MachineFunctionProperties::Property::NoVRegs
);
233 StringRef
getPassName() const override
{
234 return ARM_CP_ISLANDS_OPT_NAME
;
238 void doInitialConstPlacement(std::vector
<MachineInstr
*> &CPEMIs
);
239 void doInitialJumpTablePlacement(std::vector
<MachineInstr
*> &CPEMIs
);
240 bool BBHasFallthrough(MachineBasicBlock
*MBB
);
241 CPEntry
*findConstPoolEntry(unsigned CPI
, const MachineInstr
*CPEMI
);
242 unsigned getCPELogAlign(const MachineInstr
*CPEMI
);
243 void scanFunctionJumpTables();
244 void initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
);
245 MachineBasicBlock
*splitBlockBeforeInstr(MachineInstr
*MI
);
246 void updateForInsertedWaterBlock(MachineBasicBlock
*NewBB
);
247 bool decrementCPEReferenceCount(unsigned CPI
, MachineInstr
* CPEMI
);
248 unsigned getCombinedIndex(const MachineInstr
*CPEMI
);
249 int findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
);
250 bool findAvailableWater(CPUser
&U
, unsigned UserOffset
,
251 water_iterator
&WaterIter
, bool CloserWater
);
252 void createNewWater(unsigned CPUserIndex
, unsigned UserOffset
,
253 MachineBasicBlock
*&NewMBB
);
254 bool handleConstantPoolUser(unsigned CPUserIndex
, bool CloserWater
);
255 void removeDeadCPEMI(MachineInstr
*CPEMI
);
256 bool removeUnusedCPEntries();
257 bool isCPEntryInRange(MachineInstr
*MI
, unsigned UserOffset
,
258 MachineInstr
*CPEMI
, unsigned Disp
, bool NegOk
,
259 bool DoDump
= false);
260 bool isWaterInRange(unsigned UserOffset
, MachineBasicBlock
*Water
,
261 CPUser
&U
, unsigned &Growth
);
262 bool fixupImmediateBr(ImmBranch
&Br
);
263 bool fixupConditionalBr(ImmBranch
&Br
);
264 bool fixupUnconditionalBr(ImmBranch
&Br
);
265 bool undoLRSpillRestore();
266 bool optimizeThumb2Instructions();
267 bool optimizeThumb2Branches();
268 bool reorderThumb2JumpTables();
269 bool preserveBaseRegister(MachineInstr
*JumpMI
, MachineInstr
*LEAMI
,
270 unsigned &DeadSize
, bool &CanDeleteLEA
,
272 bool optimizeThumb2JumpTables();
273 MachineBasicBlock
*adjustJTTargetBlockForward(MachineBasicBlock
*BB
,
274 MachineBasicBlock
*JTBB
);
276 unsigned getUserOffset(CPUser
&) const;
280 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
281 unsigned Disp
, bool NegativeOK
, bool IsSoImm
= false);
282 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
284 return isOffsetInRange(UserOffset
, TrialOffset
,
285 U
.getMaxDisp(), U
.NegOk
, U
.IsSoImm
);
289 } // end anonymous namespace
291 char ARMConstantIslands::ID
= 0;
293 /// verify - check BBOffsets, BBSizes, alignment of islands
294 void ARMConstantIslands::verify() {
296 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
297 assert(std::is_sorted(MF
->begin(), MF
->end(),
298 [&BBInfo
](const MachineBasicBlock
&LHS
,
299 const MachineBasicBlock
&RHS
) {
300 return BBInfo
[LHS
.getNumber()].postOffset() <
301 BBInfo
[RHS
.getNumber()].postOffset();
303 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers
.size() << " CP users.\n");
304 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
) {
305 CPUser
&U
= CPUsers
[i
];
306 unsigned UserOffset
= getUserOffset(U
);
307 // Verify offset using the real max displacement without the safety
309 if (isCPEntryInRange(U
.MI
, UserOffset
, U
.CPEMI
, U
.getMaxDisp()+2, U
.NegOk
,
310 /* DoDump = */ true)) {
311 LLVM_DEBUG(dbgs() << "OK\n");
314 LLVM_DEBUG(dbgs() << "Out of range.\n");
316 LLVM_DEBUG(MF
->dump());
317 llvm_unreachable("Constant pool entry out of range!");
322 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
323 /// print block size and offset information - debugging
324 LLVM_DUMP_METHOD
void ARMConstantIslands::dumpBBs() {
325 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
327 for (unsigned J
= 0, E
= BBInfo
.size(); J
!=E
; ++J
) {
328 const BasicBlockInfo
&BBI
= BBInfo
[J
];
329 dbgs() << format("%08x %bb.%u\t", BBI
.Offset
, J
)
330 << " kb=" << unsigned(BBI
.KnownBits
)
331 << " ua=" << unsigned(BBI
.Unalign
)
332 << " pa=" << unsigned(BBI
.PostAlign
)
333 << format(" size=%#x\n", BBInfo
[J
].Size
);
339 bool ARMConstantIslands::runOnMachineFunction(MachineFunction
&mf
) {
341 MCP
= mf
.getConstantPool();
342 BBUtils
= std::unique_ptr
<ARMBasicBlockUtils
>(new ARMBasicBlockUtils(mf
));
344 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
345 << MCP
->getConstants().size() << " CP entries, aligned to "
346 << MCP
->getConstantPoolAlignment() << " bytes *****\n");
348 STI
= &static_cast<const ARMSubtarget
&>(MF
->getSubtarget());
349 TII
= STI
->getInstrInfo();
350 isPositionIndependentOrROPI
=
351 STI
->getTargetLowering()->isPositionIndependent() || STI
->isROPI();
352 AFI
= MF
->getInfo
<ARMFunctionInfo
>();
354 isThumb
= AFI
->isThumbFunction();
355 isThumb1
= AFI
->isThumb1OnlyFunction();
356 isThumb2
= AFI
->isThumb2Function();
359 bool GenerateTBB
= isThumb2
|| (isThumb1
&& SynthesizeThumb1TBB
);
361 // Renumber all of the machine basic blocks in the function, guaranteeing that
362 // the numbers agree with the position of the block in the function.
363 MF
->RenumberBlocks();
365 // Try to reorder and otherwise adjust the block layout to make good use
366 // of the TB[BH] instructions.
367 bool MadeChange
= false;
368 if (GenerateTBB
&& AdjustJumpTableBlocks
) {
369 scanFunctionJumpTables();
370 MadeChange
|= reorderThumb2JumpTables();
371 // Data is out of date, so clear it. It'll be re-computed later.
372 T2JumpTables
.clear();
373 // Blocks may have shifted around. Keep the numbering up to date.
374 MF
->RenumberBlocks();
377 // Perform the initial placement of the constant pool entries. To start with,
378 // we put them all at the end of the function.
379 std::vector
<MachineInstr
*> CPEMIs
;
381 doInitialConstPlacement(CPEMIs
);
383 if (MF
->getJumpTableInfo())
384 doInitialJumpTablePlacement(CPEMIs
);
386 /// The next UID to take is the first unused one.
387 AFI
->initPICLabelUId(CPEMIs
.size());
389 // Do the initial scan of the function, building up information about the
390 // sizes of each block, the location of all the water, and finding all of the
391 // constant pool users.
392 initializeFunctionInfo(CPEMIs
);
394 LLVM_DEBUG(dumpBBs());
396 // Functions with jump tables need an alignment of 4 because they use the ADR
397 // instruction, which aligns the PC to 4 bytes before adding an offset.
398 if (!T2JumpTables
.empty())
399 MF
->ensureAlignment(llvm::Align(4));
401 /// Remove dead constant pool entries.
402 MadeChange
|= removeUnusedCPEntries();
404 // Iteratively place constant pool entries and fix up branches until there
406 unsigned NoCPIters
= 0, NoBRIters
= 0;
408 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters
<< '\n');
409 bool CPChange
= false;
410 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
)
411 // For most inputs, it converges in no more than 5 iterations.
412 // If it doesn't end in 10, the input may have huge BB or many CPEs.
413 // In this case, we will try different heuristics.
414 CPChange
|= handleConstantPoolUser(i
, NoCPIters
>= CPMaxIteration
/ 2);
415 if (CPChange
&& ++NoCPIters
> CPMaxIteration
)
416 report_fatal_error("Constant Island pass failed to converge!");
417 LLVM_DEBUG(dumpBBs());
419 // Clear NewWaterList now. If we split a block for branches, it should
420 // appear as "new water" for the next iteration of constant pool placement.
421 NewWaterList
.clear();
423 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters
<< '\n');
424 bool BRChange
= false;
425 for (unsigned i
= 0, e
= ImmBranches
.size(); i
!= e
; ++i
)
426 BRChange
|= fixupImmediateBr(ImmBranches
[i
]);
427 if (BRChange
&& ++NoBRIters
> 30)
428 report_fatal_error("Branch Fix Up pass failed to converge!");
429 LLVM_DEBUG(dumpBBs());
431 if (!CPChange
&& !BRChange
)
436 // Shrink 32-bit Thumb2 load and store instructions.
437 if (isThumb2
&& !STI
->prefers32BitThumb())
438 MadeChange
|= optimizeThumb2Instructions();
440 // Shrink 32-bit branch instructions.
441 if (isThumb
&& STI
->hasV8MBaselineOps())
442 MadeChange
|= optimizeThumb2Branches();
444 // Optimize jump tables using TBB / TBH.
445 if (GenerateTBB
&& !STI
->genExecuteOnly())
446 MadeChange
|= optimizeThumb2JumpTables();
448 // After a while, this might be made debug-only, but it is not expensive.
451 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
452 // undo the spill / restore of LR if possible.
453 if (isThumb
&& !HasFarJump
&& AFI
->isLRSpilledForFarJump())
454 MadeChange
|= undoLRSpillRestore();
456 // Save the mapping between original and cloned constpool entries.
457 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
458 for (unsigned j
= 0, je
= CPEntries
[i
].size(); j
!= je
; ++j
) {
459 const CPEntry
& CPE
= CPEntries
[i
][j
];
460 if (CPE
.CPEMI
&& CPE
.CPEMI
->getOperand(1).isCPI())
461 AFI
->recordCPEClone(i
, CPE
.CPI
);
465 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
471 JumpTableEntryIndices
.clear();
472 JumpTableUserIndices
.clear();
475 T2JumpTables
.clear();
480 /// Perform the initial placement of the regular constant pool entries.
481 /// To start with, we put them all at the end of the function.
483 ARMConstantIslands::doInitialConstPlacement(std::vector
<MachineInstr
*> &CPEMIs
) {
484 // Create the basic block to hold the CPE's.
485 MachineBasicBlock
*BB
= MF
->CreateMachineBasicBlock();
488 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
489 unsigned MaxLogAlign
= Log2_32(MCP
->getConstantPoolAlignment());
491 // Mark the basic block as required by the const-pool.
492 BB
->setLogAlignment(MaxLogAlign
);
494 // The function needs to be as aligned as the basic blocks. The linker may
495 // move functions around based on their alignment.
496 MF
->ensureAlignment(BB
->getAlignment());
498 // Order the entries in BB by descending alignment. That ensures correct
499 // alignment of all entries as long as BB is sufficiently aligned. Keep
500 // track of the insertion point for each alignment. We are going to bucket
501 // sort the entries as they are created.
502 SmallVector
<MachineBasicBlock::iterator
, 8> InsPoint(MaxLogAlign
+ 1,
505 // Add all of the constants from the constant pool to the end block, use an
506 // identity mapping of CPI's to CPE's.
507 const std::vector
<MachineConstantPoolEntry
> &CPs
= MCP
->getConstants();
509 const DataLayout
&TD
= MF
->getDataLayout();
510 for (unsigned i
= 0, e
= CPs
.size(); i
!= e
; ++i
) {
511 unsigned Size
= TD
.getTypeAllocSize(CPs
[i
].getType());
512 unsigned Align
= CPs
[i
].getAlignment();
513 assert(isPowerOf2_32(Align
) && "Invalid alignment");
514 // Verify that all constant pool entries are a multiple of their alignment.
515 // If not, we would have to pad them out so that instructions stay aligned.
516 assert((Size
% Align
) == 0 && "CP Entry not multiple of 4 bytes!");
518 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
519 unsigned LogAlign
= Log2_32(Align
);
520 MachineBasicBlock::iterator InsAt
= InsPoint
[LogAlign
];
521 MachineInstr
*CPEMI
=
522 BuildMI(*BB
, InsAt
, DebugLoc(), TII
->get(ARM::CONSTPOOL_ENTRY
))
523 .addImm(i
).addConstantPoolIndex(i
).addImm(Size
);
524 CPEMIs
.push_back(CPEMI
);
526 // Ensure that future entries with higher alignment get inserted before
527 // CPEMI. This is bucket sort with iterators.
528 for (unsigned a
= LogAlign
+ 1; a
<= MaxLogAlign
; ++a
)
529 if (InsPoint
[a
] == InsAt
)
532 // Add a new CPEntry, but no corresponding CPUser yet.
533 CPEntries
.emplace_back(1, CPEntry(CPEMI
, i
));
535 LLVM_DEBUG(dbgs() << "Moved CPI#" << i
<< " to end of function, size = "
536 << Size
<< ", align = " << Align
<< '\n');
538 LLVM_DEBUG(BB
->dump());
541 /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
542 /// instructions can be made more efficient if the jump table immediately
543 /// follows the instruction, it's best to place them immediately next to their
544 /// jumps to begin with. In almost all cases they'll never be moved from that
546 void ARMConstantIslands::doInitialJumpTablePlacement(
547 std::vector
<MachineInstr
*> &CPEMIs
) {
548 unsigned i
= CPEntries
.size();
549 auto MJTI
= MF
->getJumpTableInfo();
550 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
552 MachineBasicBlock
*LastCorrectlyNumberedBB
= nullptr;
553 for (MachineBasicBlock
&MBB
: *MF
) {
554 auto MI
= MBB
.getLastNonDebugInstr();
559 switch (MI
->getOpcode()) {
565 case ARM::BR_JTm_i12
:
567 JTOpcode
= ARM::JUMPTABLE_ADDRS
;
570 JTOpcode
= ARM::JUMPTABLE_INSTS
;
574 JTOpcode
= ARM::JUMPTABLE_TBB
;
578 JTOpcode
= ARM::JUMPTABLE_TBH
;
582 unsigned NumOps
= MI
->getDesc().getNumOperands();
583 MachineOperand JTOp
=
584 MI
->getOperand(NumOps
- (MI
->isPredicable() ? 2 : 1));
585 unsigned JTI
= JTOp
.getIndex();
586 unsigned Size
= JT
[JTI
].MBBs
.size() * sizeof(uint32_t);
587 MachineBasicBlock
*JumpTableBB
= MF
->CreateMachineBasicBlock();
588 MF
->insert(std::next(MachineFunction::iterator(MBB
)), JumpTableBB
);
589 MachineInstr
*CPEMI
= BuildMI(*JumpTableBB
, JumpTableBB
->begin(),
590 DebugLoc(), TII
->get(JTOpcode
))
592 .addJumpTableIndex(JTI
)
594 CPEMIs
.push_back(CPEMI
);
595 CPEntries
.emplace_back(1, CPEntry(CPEMI
, JTI
));
596 JumpTableEntryIndices
.insert(std::make_pair(JTI
, CPEntries
.size() - 1));
597 if (!LastCorrectlyNumberedBB
)
598 LastCorrectlyNumberedBB
= &MBB
;
601 // If we did anything then we need to renumber the subsequent blocks.
602 if (LastCorrectlyNumberedBB
)
603 MF
->RenumberBlocks(LastCorrectlyNumberedBB
);
606 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
607 /// into the block immediately after it.
608 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock
*MBB
) {
609 // Get the next machine basic block in the function.
610 MachineFunction::iterator MBBI
= MBB
->getIterator();
611 // Can't fall off end of function.
612 if (std::next(MBBI
) == MBB
->getParent()->end())
615 MachineBasicBlock
*NextBB
= &*std::next(MBBI
);
616 if (!MBB
->isSuccessor(NextBB
))
619 // Try to analyze the end of the block. A potential fallthrough may already
620 // have an unconditional branch for whatever reason.
621 MachineBasicBlock
*TBB
, *FBB
;
622 SmallVector
<MachineOperand
, 4> Cond
;
623 bool TooDifficult
= TII
->analyzeBranch(*MBB
, TBB
, FBB
, Cond
);
624 return TooDifficult
|| FBB
== nullptr;
627 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
628 /// look up the corresponding CPEntry.
629 ARMConstantIslands::CPEntry
*
630 ARMConstantIslands::findConstPoolEntry(unsigned CPI
,
631 const MachineInstr
*CPEMI
) {
632 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
633 // Number of entries per constpool index should be small, just do a
635 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
636 if (CPEs
[i
].CPEMI
== CPEMI
)
642 /// getCPELogAlign - Returns the required alignment of the constant pool entry
643 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
644 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr
*CPEMI
) {
645 switch (CPEMI
->getOpcode()) {
646 case ARM::CONSTPOOL_ENTRY
:
648 case ARM::JUMPTABLE_TBB
:
649 return isThumb1
? 2 : 0;
650 case ARM::JUMPTABLE_TBH
:
651 return isThumb1
? 2 : 1;
652 case ARM::JUMPTABLE_INSTS
:
654 case ARM::JUMPTABLE_ADDRS
:
657 llvm_unreachable("unknown constpool entry kind");
660 unsigned CPI
= getCombinedIndex(CPEMI
);
661 assert(CPI
< MCP
->getConstants().size() && "Invalid constant pool index.");
662 unsigned Align
= MCP
->getConstants()[CPI
].getAlignment();
663 assert(isPowerOf2_32(Align
) && "Invalid CPE alignment");
664 return Log2_32(Align
);
667 /// scanFunctionJumpTables - Do a scan of the function, building up
668 /// information about the sizes of each block and the locations of all
670 void ARMConstantIslands::scanFunctionJumpTables() {
671 for (MachineBasicBlock
&MBB
: *MF
) {
672 for (MachineInstr
&I
: MBB
)
674 (I
.getOpcode() == ARM::t2BR_JT
|| I
.getOpcode() == ARM::tBR_JTr
))
675 T2JumpTables
.push_back(&I
);
679 /// initializeFunctionInfo - Do the initial scan of the function, building up
680 /// information about the sizes of each block, the location of all the water,
681 /// and finding all of the constant pool users.
682 void ARMConstantIslands::
683 initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
) {
685 BBUtils
->computeAllBlockSizes();
686 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
687 // The known bits of the entry block offset are determined by the function
689 BBInfo
.front().KnownBits
= Log2(MF
->getAlignment());
691 // Compute block offsets and known bits.
692 BBUtils
->adjustBBOffsetsAfter(&MF
->front());
694 // Now go back through the instructions and build up our data structures.
695 for (MachineBasicBlock
&MBB
: *MF
) {
696 // If this block doesn't fall through into the next MBB, then this is
697 // 'water' that a constant pool island could be placed.
698 if (!BBHasFallthrough(&MBB
))
699 WaterList
.push_back(&MBB
);
701 for (MachineInstr
&I
: MBB
) {
702 if (I
.isDebugInstr())
705 unsigned Opc
= I
.getOpcode();
713 continue; // Ignore other JT branches
716 T2JumpTables
.push_back(&I
);
717 continue; // Does not get an entry in ImmBranches
748 // Record this immediate branch.
749 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
750 ImmBranches
.push_back(ImmBranch(&I
, MaxOffs
, isCond
, UOpc
));
753 if (Opc
== ARM::tPUSH
|| Opc
== ARM::tPOP_RET
)
754 PushPopMIs
.push_back(&I
);
756 if (Opc
== ARM::CONSTPOOL_ENTRY
|| Opc
== ARM::JUMPTABLE_ADDRS
||
757 Opc
== ARM::JUMPTABLE_INSTS
|| Opc
== ARM::JUMPTABLE_TBB
||
758 Opc
== ARM::JUMPTABLE_TBH
)
761 // Scan the instructions for constant pool operands.
762 for (unsigned op
= 0, e
= I
.getNumOperands(); op
!= e
; ++op
)
763 if (I
.getOperand(op
).isCPI() || I
.getOperand(op
).isJTI()) {
764 // We found one. The addressing mode tells us the max displacement
765 // from the PC that this instruction permits.
767 // Basic size info comes from the TSFlags field.
771 bool IsSoImm
= false;
775 llvm_unreachable("Unknown addressing mode for CP reference!");
777 // Taking the address of a CP entry.
779 case ARM::LEApcrelJT
:
780 // This takes a SoImm, which is 8 bit immediate rotated. We'll
781 // pretend the maximum offset is 255 * 4. Since each instruction
782 // 4 byte wide, this is always correct. We'll check for other
783 // displacements that fits in a SoImm as well.
789 case ARM::t2LEApcrel
:
790 case ARM::t2LEApcrelJT
:
795 case ARM::tLEApcrelJT
:
806 Bits
= 12; // +-offset_12
812 Scale
= 4; // +(offset_8*4)
818 Scale
= 4; // +-(offset_8*4)
823 Scale
= 2; // +-(offset_8*2)
828 // Remember that this is a user of a CP entry.
829 unsigned CPI
= I
.getOperand(op
).getIndex();
830 if (I
.getOperand(op
).isJTI()) {
831 JumpTableUserIndices
.insert(std::make_pair(CPI
, CPUsers
.size()));
832 CPI
= JumpTableEntryIndices
[CPI
];
835 MachineInstr
*CPEMI
= CPEMIs
[CPI
];
836 unsigned MaxOffs
= ((1 << Bits
)-1) * Scale
;
837 CPUsers
.push_back(CPUser(&I
, CPEMI
, MaxOffs
, NegOk
, IsSoImm
));
839 // Increment corresponding CPEntry reference count.
840 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
841 assert(CPE
&& "Cannot find a corresponding CPEntry!");
844 // Instructions can only use one CP entry, don't bother scanning the
845 // rest of the operands.
852 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
854 static bool CompareMBBNumbers(const MachineBasicBlock
*LHS
,
855 const MachineBasicBlock
*RHS
) {
856 return LHS
->getNumber() < RHS
->getNumber();
859 /// updateForInsertedWaterBlock - When a block is newly inserted into the
860 /// machine function, it upsets all of the block numbers. Renumber the blocks
861 /// and update the arrays that parallel this numbering.
862 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock
*NewBB
) {
863 // Renumber the MBB's to keep them consecutive.
864 NewBB
->getParent()->RenumberBlocks(NewBB
);
866 // Insert an entry into BBInfo to align it properly with the (newly
867 // renumbered) block numbers.
868 BBUtils
->insert(NewBB
->getNumber(), BasicBlockInfo());
870 // Next, update WaterList. Specifically, we need to add NewMBB as having
871 // available water after it.
872 water_iterator IP
= llvm::lower_bound(WaterList
, NewBB
, CompareMBBNumbers
);
873 WaterList
.insert(IP
, NewBB
);
876 /// Split the basic block containing MI into two blocks, which are joined by
877 /// an unconditional branch. Update data structures and renumber blocks to
878 /// account for this change and returns the newly created block.
879 MachineBasicBlock
*ARMConstantIslands::splitBlockBeforeInstr(MachineInstr
*MI
) {
880 MachineBasicBlock
*OrigBB
= MI
->getParent();
882 // Collect liveness information at MI.
883 LivePhysRegs
LRs(*MF
->getSubtarget().getRegisterInfo());
884 LRs
.addLiveOuts(*OrigBB
);
885 auto LivenessEnd
= ++MachineBasicBlock::iterator(MI
).getReverse();
886 for (MachineInstr
&LiveMI
: make_range(OrigBB
->rbegin(), LivenessEnd
))
887 LRs
.stepBackward(LiveMI
);
889 // Create a new MBB for the code after the OrigBB.
890 MachineBasicBlock
*NewBB
=
891 MF
->CreateMachineBasicBlock(OrigBB
->getBasicBlock());
892 MachineFunction::iterator MBBI
= ++OrigBB
->getIterator();
893 MF
->insert(MBBI
, NewBB
);
895 // Splice the instructions starting with MI over to NewBB.
896 NewBB
->splice(NewBB
->end(), OrigBB
, MI
, OrigBB
->end());
898 // Add an unconditional branch from OrigBB to NewBB.
899 // Note the new unconditional branch is not being recorded.
900 // There doesn't seem to be meaningful DebugInfo available; this doesn't
901 // correspond to anything in the source.
902 unsigned Opc
= isThumb
? (isThumb2
? ARM::t2B
: ARM::tB
) : ARM::B
;
904 BuildMI(OrigBB
, DebugLoc(), TII
->get(Opc
)).addMBB(NewBB
);
906 BuildMI(OrigBB
, DebugLoc(), TII
->get(Opc
))
908 .add(predOps(ARMCC::AL
));
911 // Update the CFG. All succs of OrigBB are now succs of NewBB.
912 NewBB
->transferSuccessors(OrigBB
);
914 // OrigBB branches to NewBB.
915 OrigBB
->addSuccessor(NewBB
);
917 // Update live-in information in the new block.
918 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
919 for (MCPhysReg L
: LRs
)
920 if (!MRI
.isReserved(L
))
923 // Update internal data structures to account for the newly inserted MBB.
924 // This is almost the same as updateForInsertedWaterBlock, except that
925 // the Water goes after OrigBB, not NewBB.
926 MF
->RenumberBlocks(NewBB
);
928 // Insert an entry into BBInfo to align it properly with the (newly
929 // renumbered) block numbers.
930 BBUtils
->insert(NewBB
->getNumber(), BasicBlockInfo());
932 // Next, update WaterList. Specifically, we need to add OrigMBB as having
933 // available water after it (but not if it's already there, which happens
934 // when splitting before a conditional branch that is followed by an
935 // unconditional branch - in that case we want to insert NewBB).
936 water_iterator IP
= llvm::lower_bound(WaterList
, OrigBB
, CompareMBBNumbers
);
937 MachineBasicBlock
* WaterBB
= *IP
;
938 if (WaterBB
== OrigBB
)
939 WaterList
.insert(std::next(IP
), NewBB
);
941 WaterList
.insert(IP
, OrigBB
);
942 NewWaterList
.insert(OrigBB
);
944 // Figure out how large the OrigBB is. As the first half of the original
945 // block, it cannot contain a tablejump. The size includes
946 // the new jump we added. (It should be possible to do this without
947 // recounting everything, but it's very confusing, and this is rarely
949 BBUtils
->computeBlockSize(OrigBB
);
951 // Figure out how large the NewMBB is. As the second half of the original
952 // block, it may contain a tablejump.
953 BBUtils
->computeBlockSize(NewBB
);
955 // All BBOffsets following these blocks must be modified.
956 BBUtils
->adjustBBOffsetsAfter(OrigBB
);
961 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
962 /// displacement computation. Update U.KnownAlignment to match its current
963 /// basic block location.
964 unsigned ARMConstantIslands::getUserOffset(CPUser
&U
) const {
965 unsigned UserOffset
= BBUtils
->getOffsetOf(U
.MI
);
967 SmallVectorImpl
<BasicBlockInfo
> &BBInfo
= BBUtils
->getBBInfo();
968 const BasicBlockInfo
&BBI
= BBInfo
[U
.MI
->getParent()->getNumber()];
969 unsigned KnownBits
= BBI
.internalKnownBits();
971 // The value read from PC is offset from the actual instruction address.
972 UserOffset
+= (isThumb
? 4 : 8);
974 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
975 // Make sure U.getMaxDisp() returns a constrained range.
976 U
.KnownAlignment
= (KnownBits
>= 2);
978 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
979 // purposes of the displacement computation; compensate for that here.
980 // For unknown alignments, getMaxDisp() constrains the range instead.
981 if (isThumb
&& U
.KnownAlignment
)
987 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
988 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
989 /// constant pool entry).
990 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
991 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
992 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
993 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset
,
994 unsigned TrialOffset
, unsigned MaxDisp
,
995 bool NegativeOK
, bool IsSoImm
) {
996 if (UserOffset
<= TrialOffset
) {
997 // User before the Trial.
998 if (TrialOffset
- UserOffset
<= MaxDisp
)
1000 // FIXME: Make use full range of soimm values.
1001 } else if (NegativeOK
) {
1002 if (UserOffset
- TrialOffset
<= MaxDisp
)
1004 // FIXME: Make use full range of soimm values.
1009 /// isWaterInRange - Returns true if a CPE placed after the specified
1010 /// Water (a basic block) will be in range for the specific MI.
1012 /// Compute how much the function will grow by inserting a CPE after Water.
1013 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset
,
1014 MachineBasicBlock
* Water
, CPUser
&U
,
1016 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1017 unsigned CPELogAlign
= getCPELogAlign(U
.CPEMI
);
1018 unsigned CPEOffset
= BBInfo
[Water
->getNumber()].postOffset(CPELogAlign
);
1019 unsigned NextBlockOffset
, NextBlockLogAlignment
;
1020 MachineFunction::const_iterator NextBlock
= Water
->getIterator();
1021 if (++NextBlock
== MF
->end()) {
1022 NextBlockOffset
= BBInfo
[Water
->getNumber()].postOffset();
1023 NextBlockLogAlignment
= 0;
1025 NextBlockOffset
= BBInfo
[NextBlock
->getNumber()].Offset
;
1026 NextBlockLogAlignment
= NextBlock
->getLogAlignment();
1028 unsigned Size
= U
.CPEMI
->getOperand(2).getImm();
1029 unsigned CPEEnd
= CPEOffset
+ Size
;
1031 // The CPE may be able to hide in the alignment padding before the next
1032 // block. It may also cause more padding to be required if it is more aligned
1033 // that the next block.
1034 if (CPEEnd
> NextBlockOffset
) {
1035 Growth
= CPEEnd
- NextBlockOffset
;
1036 // Compute the padding that would go at the end of the CPE to align the next
1038 Growth
+= OffsetToAlignment(CPEEnd
, 1ULL << NextBlockLogAlignment
);
1040 // If the CPE is to be inserted before the instruction, that will raise
1041 // the offset of the instruction. Also account for unknown alignment padding
1042 // in blocks between CPE and the user.
1043 if (CPEOffset
< UserOffset
)
1045 Growth
+ UnknownPadding(Log2(MF
->getAlignment()), CPELogAlign
);
1047 // CPE fits in existing padding.
1050 return isOffsetInRange(UserOffset
, CPEOffset
, U
);
1053 /// isCPEntryInRange - Returns true if the distance between specific MI and
1054 /// specific ConstPool entry instruction can fit in MI's displacement field.
1055 bool ARMConstantIslands::isCPEntryInRange(MachineInstr
*MI
, unsigned UserOffset
,
1056 MachineInstr
*CPEMI
, unsigned MaxDisp
,
1057 bool NegOk
, bool DoDump
) {
1058 unsigned CPEOffset
= BBUtils
->getOffsetOf(CPEMI
);
1062 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1063 unsigned Block
= MI
->getParent()->getNumber();
1064 const BasicBlockInfo
&BBI
= BBInfo
[Block
];
1065 dbgs() << "User of CPE#" << CPEMI
->getOperand(0).getImm()
1066 << " max delta=" << MaxDisp
1067 << format(" insn address=%#x", UserOffset
) << " in "
1068 << printMBBReference(*MI
->getParent()) << ": "
1069 << format("%#x-%x\t", BBI
.Offset
, BBI
.postOffset()) << *MI
1070 << format("CPE address=%#x offset=%+d: ", CPEOffset
,
1071 int(CPEOffset
- UserOffset
));
1075 return isOffsetInRange(UserOffset
, CPEOffset
, MaxDisp
, NegOk
);
1079 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1080 /// unconditionally branches to its only successor.
1081 static bool BBIsJumpedOver(MachineBasicBlock
*MBB
) {
1082 if (MBB
->pred_size() != 1 || MBB
->succ_size() != 1)
1085 MachineBasicBlock
*Succ
= *MBB
->succ_begin();
1086 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
1087 MachineInstr
*PredMI
= &Pred
->back();
1088 if (PredMI
->getOpcode() == ARM::B
|| PredMI
->getOpcode() == ARM::tB
1089 || PredMI
->getOpcode() == ARM::t2B
)
1090 return PredMI
->getOperand(0).getMBB() == Succ
;
1095 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1096 /// and instruction CPEMI, and decrement its refcount. If the refcount
1097 /// becomes 0 remove the entry and instruction. Returns true if we removed
1098 /// the entry, false if we didn't.
1099 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI
,
1100 MachineInstr
*CPEMI
) {
1101 // Find the old entry. Eliminate it if it is no longer used.
1102 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
1103 assert(CPE
&& "Unexpected!");
1104 if (--CPE
->RefCount
== 0) {
1105 removeDeadCPEMI(CPEMI
);
1106 CPE
->CPEMI
= nullptr;
1113 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr
*CPEMI
) {
1114 if (CPEMI
->getOperand(1).isCPI())
1115 return CPEMI
->getOperand(1).getIndex();
1117 return JumpTableEntryIndices
[CPEMI
->getOperand(1).getIndex()];
1120 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1121 /// if not, see if an in-range clone of the CPE is in range, and if so,
1122 /// change the data structures so the user references the clone. Returns:
1123 /// 0 = no existing entry found
1124 /// 1 = entry found, and there were no code insertions or deletions
1125 /// 2 = entry found, and there were code insertions or deletions
1126 int ARMConstantIslands::findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
) {
1127 MachineInstr
*UserMI
= U
.MI
;
1128 MachineInstr
*CPEMI
= U
.CPEMI
;
1130 // Check to see if the CPE is already in-range.
1131 if (isCPEntryInRange(UserMI
, UserOffset
, CPEMI
, U
.getMaxDisp(), U
.NegOk
,
1133 LLVM_DEBUG(dbgs() << "In range\n");
1137 // No. Look for previously created clones of the CPE that are in range.
1138 unsigned CPI
= getCombinedIndex(CPEMI
);
1139 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
1140 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
1141 // We already tried this one
1142 if (CPEs
[i
].CPEMI
== CPEMI
)
1144 // Removing CPEs can leave empty entries, skip
1145 if (CPEs
[i
].CPEMI
== nullptr)
1147 if (isCPEntryInRange(UserMI
, UserOffset
, CPEs
[i
].CPEMI
, U
.getMaxDisp(),
1149 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI
<< " with CPE#"
1150 << CPEs
[i
].CPI
<< "\n");
1151 // Point the CPUser node to the replacement
1152 U
.CPEMI
= CPEs
[i
].CPEMI
;
1153 // Change the CPI in the instruction operand to refer to the clone.
1154 for (unsigned j
= 0, e
= UserMI
->getNumOperands(); j
!= e
; ++j
)
1155 if (UserMI
->getOperand(j
).isCPI()) {
1156 UserMI
->getOperand(j
).setIndex(CPEs
[i
].CPI
);
1159 // Adjust the refcount of the clone...
1161 // ...and the original. If we didn't remove the old entry, none of the
1162 // addresses changed, so we don't need another pass.
1163 return decrementCPEReferenceCount(CPI
, CPEMI
) ? 2 : 1;
1169 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1170 /// the specific unconditional branch instruction.
1171 static inline unsigned getUnconditionalBrDisp(int Opc
) {
1174 return ((1<<10)-1)*2;
1176 return ((1<<23)-1)*2;
1181 return ((1<<23)-1)*4;
1184 /// findAvailableWater - Look for an existing entry in the WaterList in which
1185 /// we can place the CPE referenced from U so it's within range of U's MI.
1186 /// Returns true if found, false if not. If it returns true, WaterIter
1187 /// is set to the WaterList entry. For Thumb, prefer water that will not
1188 /// introduce padding to water that will. To ensure that this pass
1189 /// terminates, the CPE location for a particular CPUser is only allowed to
1190 /// move to a lower address, so search backward from the end of the list and
1191 /// prefer the first water that is in range.
1192 bool ARMConstantIslands::findAvailableWater(CPUser
&U
, unsigned UserOffset
,
1193 water_iterator
&WaterIter
,
1195 if (WaterList
.empty())
1198 unsigned BestGrowth
= ~0u;
1199 // The nearest water without splitting the UserBB is right after it.
1200 // If the distance is still large (we have a big BB), then we need to split it
1201 // if we don't converge after certain iterations. This helps the following
1202 // situation to converge:
1207 // When a CP access is out of range, BB0 may be used as water. However,
1208 // inserting islands between BB0 and BB1 makes other accesses out of range.
1209 MachineBasicBlock
*UserBB
= U
.MI
->getParent();
1210 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1211 unsigned MinNoSplitDisp
=
1212 BBInfo
[UserBB
->getNumber()].postOffset(getCPELogAlign(U
.CPEMI
));
1213 if (CloserWater
&& MinNoSplitDisp
> U
.getMaxDisp() / 2)
1215 for (water_iterator IP
= std::prev(WaterList
.end()), B
= WaterList
.begin();;
1217 MachineBasicBlock
* WaterBB
= *IP
;
1218 // Check if water is in range and is either at a lower address than the
1219 // current "high water mark" or a new water block that was created since
1220 // the previous iteration by inserting an unconditional branch. In the
1221 // latter case, we want to allow resetting the high water mark back to
1222 // this new water since we haven't seen it before. Inserting branches
1223 // should be relatively uncommon and when it does happen, we want to be
1224 // sure to take advantage of it for all the CPEs near that block, so that
1225 // we don't insert more branches than necessary.
1226 // When CloserWater is true, we try to find the lowest address after (or
1227 // equal to) user MI's BB no matter of padding growth.
1229 if (isWaterInRange(UserOffset
, WaterBB
, U
, Growth
) &&
1230 (WaterBB
->getNumber() < U
.HighWaterMark
->getNumber() ||
1231 NewWaterList
.count(WaterBB
) || WaterBB
== U
.MI
->getParent()) &&
1232 Growth
< BestGrowth
) {
1233 // This is the least amount of required padding seen so far.
1234 BestGrowth
= Growth
;
1236 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB
)
1237 << " Growth=" << Growth
<< '\n');
1239 if (CloserWater
&& WaterBB
== U
.MI
->getParent())
1241 // Keep looking unless it is perfect and we're not looking for the lowest
1242 // possible address.
1243 if (!CloserWater
&& BestGrowth
== 0)
1249 return BestGrowth
!= ~0u;
1252 /// createNewWater - No existing WaterList entry will work for
1253 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1254 /// block is used if in range, and the conditional branch munged so control
1255 /// flow is correct. Otherwise the block is split to create a hole with an
1256 /// unconditional branch around it. In either case NewMBB is set to a
1257 /// block following which the new island can be inserted (the WaterList
1258 /// is not adjusted).
1259 void ARMConstantIslands::createNewWater(unsigned CPUserIndex
,
1260 unsigned UserOffset
,
1261 MachineBasicBlock
*&NewMBB
) {
1262 CPUser
&U
= CPUsers
[CPUserIndex
];
1263 MachineInstr
*UserMI
= U
.MI
;
1264 MachineInstr
*CPEMI
= U
.CPEMI
;
1265 unsigned CPELogAlign
= getCPELogAlign(CPEMI
);
1266 MachineBasicBlock
*UserMBB
= UserMI
->getParent();
1267 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1268 const BasicBlockInfo
&UserBBI
= BBInfo
[UserMBB
->getNumber()];
1270 // If the block does not end in an unconditional branch already, and if the
1271 // end of the block is within range, make new water there. (The addition
1272 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1273 // Thumb2, 2 on Thumb1.
1274 if (BBHasFallthrough(UserMBB
)) {
1275 // Size of branch to insert.
1276 unsigned Delta
= isThumb1
? 2 : 4;
1277 // Compute the offset where the CPE will begin.
1278 unsigned CPEOffset
= UserBBI
.postOffset(CPELogAlign
) + Delta
;
1280 if (isOffsetInRange(UserOffset
, CPEOffset
, U
)) {
1281 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB
)
1282 << format(", expected CPE offset %#x\n", CPEOffset
));
1283 NewMBB
= &*++UserMBB
->getIterator();
1284 // Add an unconditional branch from UserMBB to fallthrough block. Record
1285 // it for branch lengthening; this new branch will not get out of range,
1286 // but if the preceding conditional branch is out of range, the targets
1287 // will be exchanged, and the altered branch may be out of range, so the
1288 // machinery has to know about it.
1289 int UncondBr
= isThumb
? ((isThumb2
) ? ARM::t2B
: ARM::tB
) : ARM::B
;
1291 BuildMI(UserMBB
, DebugLoc(), TII
->get(UncondBr
)).addMBB(NewMBB
);
1293 BuildMI(UserMBB
, DebugLoc(), TII
->get(UncondBr
))
1295 .add(predOps(ARMCC::AL
));
1296 unsigned MaxDisp
= getUnconditionalBrDisp(UncondBr
);
1297 ImmBranches
.push_back(ImmBranch(&UserMBB
->back(),
1298 MaxDisp
, false, UncondBr
));
1299 BBUtils
->computeBlockSize(UserMBB
);
1300 BBUtils
->adjustBBOffsetsAfter(UserMBB
);
1305 // What a big block. Find a place within the block to split it. This is a
1306 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1307 // entries are 4 bytes: if instruction I references island CPE, and
1308 // instruction I+1 references CPE', it will not work well to put CPE as far
1309 // forward as possible, since then CPE' cannot immediately follow it (that
1310 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1311 // need to create a new island. So, we make a first guess, then walk through
1312 // the instructions between the one currently being looked at and the
1313 // possible insertion point, and make sure any other instructions that
1314 // reference CPEs will be able to use the same island area; if not, we back
1315 // up the insertion point.
1317 // Try to split the block so it's fully aligned. Compute the latest split
1318 // point where we can add a 4-byte branch instruction, and then align to
1319 // LogAlign which is the largest possible alignment in the function.
1320 unsigned LogAlign
= Log2(MF
->getAlignment());
1321 assert(LogAlign
>= CPELogAlign
&& "Over-aligned constant pool entry");
1322 unsigned KnownBits
= UserBBI
.internalKnownBits();
1323 unsigned UPad
= UnknownPadding(LogAlign
, KnownBits
);
1324 unsigned BaseInsertOffset
= UserOffset
+ U
.getMaxDisp() - UPad
;
1325 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1328 // The 4 in the following is for the unconditional branch we'll be inserting
1329 // (allows for long branch on Thumb1). Alignment of the island is handled
1330 // inside isOffsetInRange.
1331 BaseInsertOffset
-= 4;
1333 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset
)
1334 << " la=" << LogAlign
<< " kb=" << KnownBits
1335 << " up=" << UPad
<< '\n');
1337 // This could point off the end of the block if we've already got constant
1338 // pool entries following this block; only the last one is in the water list.
1339 // Back past any possible branches (allow for a conditional and a maximally
1340 // long unconditional).
1341 if (BaseInsertOffset
+ 8 >= UserBBI
.postOffset()) {
1342 // Ensure BaseInsertOffset is larger than the offset of the instruction
1343 // following UserMI so that the loop which searches for the split point
1344 // iterates at least once.
1346 std::max(UserBBI
.postOffset() - UPad
- 8,
1347 UserOffset
+ TII
->getInstSizeInBytes(*UserMI
) + 1);
1348 // If the CP is referenced(ie, UserOffset) is in first four instructions
1349 // after IT, this recalculated BaseInsertOffset could be in the middle of
1350 // an IT block. If it is, change the BaseInsertOffset to just after the
1351 // IT block. This still make the CP Entry is in range becuase of the
1352 // following reasons.
1353 // 1. The initial BaseseInsertOffset calculated is (UserOffset +
1354 // U.getMaxDisp() - UPad).
1355 // 2. An IT block is only at most 4 instructions plus the "it" itself (18
1357 // 3. All the relevant instructions support much larger Maximum
1359 MachineBasicBlock::iterator I
= UserMI
;
1361 for (unsigned Offset
= UserOffset
+ TII
->getInstSizeInBytes(*UserMI
),
1363 I
->getOpcode() != ARM::t2IT
&&
1364 getITInstrPredicate(*I
, PredReg
) != ARMCC::AL
;
1365 Offset
+= TII
->getInstSizeInBytes(*I
), I
= std::next(I
)) {
1367 std::max(BaseInsertOffset
, Offset
+ TII
->getInstSizeInBytes(*I
) + 1);
1368 assert(I
!= UserMBB
->end() && "Fell off end of block");
1370 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset
));
1372 unsigned EndInsertOffset
= BaseInsertOffset
+ 4 + UPad
+
1373 CPEMI
->getOperand(2).getImm();
1374 MachineBasicBlock::iterator MI
= UserMI
;
1376 unsigned CPUIndex
= CPUserIndex
+1;
1377 unsigned NumCPUsers
= CPUsers
.size();
1378 MachineInstr
*LastIT
= nullptr;
1379 for (unsigned Offset
= UserOffset
+ TII
->getInstSizeInBytes(*UserMI
);
1380 Offset
< BaseInsertOffset
;
1381 Offset
+= TII
->getInstSizeInBytes(*MI
), MI
= std::next(MI
)) {
1382 assert(MI
!= UserMBB
->end() && "Fell off end of block");
1383 if (CPUIndex
< NumCPUsers
&& CPUsers
[CPUIndex
].MI
== &*MI
) {
1384 CPUser
&U
= CPUsers
[CPUIndex
];
1385 if (!isOffsetInRange(Offset
, EndInsertOffset
, U
)) {
1386 // Shift intertion point by one unit of alignment so it is within reach.
1387 BaseInsertOffset
-= 1u << LogAlign
;
1388 EndInsertOffset
-= 1u << LogAlign
;
1390 // This is overly conservative, as we don't account for CPEMIs being
1391 // reused within the block, but it doesn't matter much. Also assume CPEs
1392 // are added in order with alignment padding. We may eventually be able
1393 // to pack the aligned CPEs better.
1394 EndInsertOffset
+= U
.CPEMI
->getOperand(2).getImm();
1398 // Remember the last IT instruction.
1399 if (MI
->getOpcode() == ARM::t2IT
)
1405 // Avoid splitting an IT block.
1407 unsigned PredReg
= 0;
1408 ARMCC::CondCodes CC
= getITInstrPredicate(*MI
, PredReg
);
1409 if (CC
!= ARMCC::AL
)
1413 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1414 // On Windows, this instruction pair is covered by one single
1415 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1416 // constant island is injected inbetween them, the relocation will clobber
1417 // the instruction and fail to update the MOVT instruction.
1418 // (These instructions are bundled up until right before the ConstantIslands
1420 if (STI
->isTargetWindows() && isThumb
&& MI
->getOpcode() == ARM::t2MOVTi16
&&
1421 (MI
->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK
) ==
1424 assert(MI
->getOpcode() == ARM::t2MOVi16
&&
1425 (MI
->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK
) ==
1429 // We really must not split an IT block.
1432 assert(!isThumb
|| getITInstrPredicate(*MI
, PredReg
) == ARMCC::AL
);
1434 NewMBB
= splitBlockBeforeInstr(&*MI
);
1437 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1438 /// is out-of-range. If so, pick up the constant pool value and move it some
1439 /// place in-range. Return true if we changed any addresses (thus must run
1440 /// another pass of branch lengthening), false otherwise.
1441 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex
,
1443 CPUser
&U
= CPUsers
[CPUserIndex
];
1444 MachineInstr
*UserMI
= U
.MI
;
1445 MachineInstr
*CPEMI
= U
.CPEMI
;
1446 unsigned CPI
= getCombinedIndex(CPEMI
);
1447 unsigned Size
= CPEMI
->getOperand(2).getImm();
1448 // Compute this only once, it's expensive.
1449 unsigned UserOffset
= getUserOffset(U
);
1451 // See if the current entry is within range, or there is a clone of it
1453 int result
= findInRangeCPEntry(U
, UserOffset
);
1454 if (result
==1) return false;
1455 else if (result
==2) return true;
1457 // No existing clone of this CPE is within range.
1458 // We will be generating a new clone. Get a UID for it.
1459 unsigned ID
= AFI
->createPICLabelUId();
1461 // Look for water where we can place this CPE.
1462 MachineBasicBlock
*NewIsland
= MF
->CreateMachineBasicBlock();
1463 MachineBasicBlock
*NewMBB
;
1465 if (findAvailableWater(U
, UserOffset
, IP
, CloserWater
)) {
1466 LLVM_DEBUG(dbgs() << "Found water in range\n");
1467 MachineBasicBlock
*WaterBB
= *IP
;
1469 // If the original WaterList entry was "new water" on this iteration,
1470 // propagate that to the new island. This is just keeping NewWaterList
1471 // updated to match the WaterList, which will be updated below.
1472 if (NewWaterList
.erase(WaterBB
))
1473 NewWaterList
.insert(NewIsland
);
1475 // The new CPE goes before the following block (NewMBB).
1476 NewMBB
= &*++WaterBB
->getIterator();
1479 LLVM_DEBUG(dbgs() << "No water found\n");
1480 createNewWater(CPUserIndex
, UserOffset
, NewMBB
);
1482 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1483 // called while handling branches so that the water will be seen on the
1484 // next iteration for constant pools, but in this context, we don't want
1485 // it. Check for this so it will be removed from the WaterList.
1486 // Also remove any entry from NewWaterList.
1487 MachineBasicBlock
*WaterBB
= &*--NewMBB
->getIterator();
1488 IP
= find(WaterList
, WaterBB
);
1489 if (IP
!= WaterList
.end())
1490 NewWaterList
.erase(WaterBB
);
1492 // We are adding new water. Update NewWaterList.
1493 NewWaterList
.insert(NewIsland
);
1495 // Always align the new block because CP entries can be smaller than 4
1496 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1497 // be an already aligned constant pool block.
1498 const unsigned LogAlign
= isThumb
? 1 : 2;
1499 if (NewMBB
->getLogAlignment() < LogAlign
)
1500 NewMBB
->setLogAlignment(LogAlign
);
1502 // Remove the original WaterList entry; we want subsequent insertions in
1503 // this vicinity to go after the one we're about to insert. This
1504 // considerably reduces the number of times we have to move the same CPE
1505 // more than once and is also important to ensure the algorithm terminates.
1506 if (IP
!= WaterList
.end())
1507 WaterList
.erase(IP
);
1509 // Okay, we know we can put an island before NewMBB now, do it!
1510 MF
->insert(NewMBB
->getIterator(), NewIsland
);
1512 // Update internal data structures to account for the newly inserted MBB.
1513 updateForInsertedWaterBlock(NewIsland
);
1515 // Now that we have an island to add the CPE to, clone the original CPE and
1516 // add it to the island.
1517 U
.HighWaterMark
= NewIsland
;
1518 U
.CPEMI
= BuildMI(NewIsland
, DebugLoc(), CPEMI
->getDesc())
1520 .add(CPEMI
->getOperand(1))
1522 CPEntries
[CPI
].push_back(CPEntry(U
.CPEMI
, ID
, 1));
1525 // Decrement the old entry, and remove it if refcount becomes 0.
1526 decrementCPEReferenceCount(CPI
, CPEMI
);
1528 // Mark the basic block as aligned as required by the const-pool entry.
1529 NewIsland
->setLogAlignment(getCPELogAlign(U
.CPEMI
));
1531 // Increase the size of the island block to account for the new entry.
1532 BBUtils
->adjustBBSize(NewIsland
, Size
);
1533 BBUtils
->adjustBBOffsetsAfter(&*--NewIsland
->getIterator());
1535 // Finally, change the CPI in the instruction operand to be ID.
1536 for (unsigned i
= 0, e
= UserMI
->getNumOperands(); i
!= e
; ++i
)
1537 if (UserMI
->getOperand(i
).isCPI()) {
1538 UserMI
->getOperand(i
).setIndex(ID
);
1543 dbgs() << " Moved CPE to #" << ID
<< " CPI=" << CPI
1544 << format(" offset=%#x\n",
1545 BBUtils
->getBBInfo()[NewIsland
->getNumber()].Offset
));
1550 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1551 /// sizes and offsets of impacted basic blocks.
1552 void ARMConstantIslands::removeDeadCPEMI(MachineInstr
*CPEMI
) {
1553 MachineBasicBlock
*CPEBB
= CPEMI
->getParent();
1554 unsigned Size
= CPEMI
->getOperand(2).getImm();
1555 CPEMI
->eraseFromParent();
1556 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1557 BBUtils
->adjustBBSize(CPEBB
, -Size
);
1558 // All succeeding offsets have the current size value added in, fix this.
1559 if (CPEBB
->empty()) {
1560 BBInfo
[CPEBB
->getNumber()].Size
= 0;
1562 // This block no longer needs to be aligned.
1563 CPEBB
->setLogAlignment(0);
1565 // Entries are sorted by descending alignment, so realign from the front.
1566 CPEBB
->setLogAlignment(getCPELogAlign(&*CPEBB
->begin()));
1568 BBUtils
->adjustBBOffsetsAfter(CPEBB
);
1569 // An island has only one predecessor BB and one successor BB. Check if
1570 // this BB's predecessor jumps directly to this BB's successor. This
1571 // shouldn't happen currently.
1572 assert(!BBIsJumpedOver(CPEBB
) && "How did this happen?");
1573 // FIXME: remove the empty blocks after all the work is done?
1576 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1578 bool ARMConstantIslands::removeUnusedCPEntries() {
1579 unsigned MadeChange
= false;
1580 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
1581 std::vector
<CPEntry
> &CPEs
= CPEntries
[i
];
1582 for (unsigned j
= 0, ee
= CPEs
.size(); j
!= ee
; ++j
) {
1583 if (CPEs
[j
].RefCount
== 0 && CPEs
[j
].CPEMI
) {
1584 removeDeadCPEMI(CPEs
[j
].CPEMI
);
1585 CPEs
[j
].CPEMI
= nullptr;
1594 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1595 /// away to fit in its displacement field.
1596 bool ARMConstantIslands::fixupImmediateBr(ImmBranch
&Br
) {
1597 MachineInstr
*MI
= Br
.MI
;
1598 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1600 // Check to see if the DestBB is already in-range.
1601 if (BBUtils
->isBBInRange(MI
, DestBB
, Br
.MaxDisp
))
1605 return fixupUnconditionalBr(Br
);
1606 return fixupConditionalBr(Br
);
1609 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1610 /// too far away to fit in its displacement field. If the LR register has been
1611 /// spilled in the epilogue, then we can use BL to implement a far jump.
1612 /// Otherwise, add an intermediate branch instruction to a branch.
1614 ARMConstantIslands::fixupUnconditionalBr(ImmBranch
&Br
) {
1615 MachineInstr
*MI
= Br
.MI
;
1616 MachineBasicBlock
*MBB
= MI
->getParent();
1618 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1620 if (!AFI
->isLRSpilled())
1621 report_fatal_error("underestimated function size");
1623 // Use BL to implement far jump.
1624 Br
.MaxDisp
= (1 << 21) * 2;
1625 MI
->setDesc(TII
->get(ARM::tBfar
));
1626 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1627 BBInfo
[MBB
->getNumber()].Size
+= 2;
1628 BBUtils
->adjustBBOffsetsAfter(MBB
);
1632 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI
);
1637 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1638 /// far away to fit in its displacement field. It is converted to an inverse
1639 /// conditional branch + an unconditional branch to the destination.
1641 ARMConstantIslands::fixupConditionalBr(ImmBranch
&Br
) {
1642 MachineInstr
*MI
= Br
.MI
;
1643 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1645 // Add an unconditional branch to the destination and invert the branch
1646 // condition to jump over it:
1652 ARMCC::CondCodes CC
= (ARMCC::CondCodes
)MI
->getOperand(1).getImm();
1653 CC
= ARMCC::getOppositeCondition(CC
);
1654 Register CCReg
= MI
->getOperand(2).getReg();
1656 // If the branch is at the end of its MBB and that has a fall-through block,
1657 // direct the updated conditional branch to the fall-through block. Otherwise,
1658 // split the MBB before the next instruction.
1659 MachineBasicBlock
*MBB
= MI
->getParent();
1660 MachineInstr
*BMI
= &MBB
->back();
1661 bool NeedSplit
= (BMI
!= MI
) || !BBHasFallthrough(MBB
);
1665 if (std::next(MachineBasicBlock::iterator(MI
)) == std::prev(MBB
->end()) &&
1666 BMI
->getOpcode() == Br
.UncondBr
) {
1667 // Last MI in the BB is an unconditional branch. Can we simply invert the
1668 // condition and swap destinations:
1674 MachineBasicBlock
*NewDest
= BMI
->getOperand(0).getMBB();
1675 if (BBUtils
->isBBInRange(MI
, NewDest
, Br
.MaxDisp
)) {
1677 dbgs() << " Invert Bcc condition and swap its destination with "
1679 BMI
->getOperand(0).setMBB(DestBB
);
1680 MI
->getOperand(0).setMBB(NewDest
);
1681 MI
->getOperand(1).setImm(CC
);
1688 splitBlockBeforeInstr(MI
);
1689 // No need for the branch to the next block. We're adding an unconditional
1690 // branch to the destination.
1691 int delta
= TII
->getInstSizeInBytes(MBB
->back());
1692 BBUtils
->adjustBBSize(MBB
, -delta
);
1693 MBB
->back().eraseFromParent();
1695 // The conditional successor will be swapped between the BBs after this, so
1697 MBB
->addSuccessor(DestBB
);
1698 std::next(MBB
->getIterator())->removeSuccessor(DestBB
);
1700 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1702 MachineBasicBlock
*NextBB
= &*++MBB
->getIterator();
1704 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB
)
1705 << " also invert condition and change dest. to "
1706 << printMBBReference(*NextBB
) << "\n");
1708 // Insert a new conditional branch and a new unconditional branch.
1709 // Also update the ImmBranch as well as adding a new entry for the new branch.
1710 BuildMI(MBB
, DebugLoc(), TII
->get(MI
->getOpcode()))
1711 .addMBB(NextBB
).addImm(CC
).addReg(CCReg
);
1712 Br
.MI
= &MBB
->back();
1713 BBUtils
->adjustBBSize(MBB
, TII
->getInstSizeInBytes(MBB
->back()));
1715 BuildMI(MBB
, DebugLoc(), TII
->get(Br
.UncondBr
))
1717 .add(predOps(ARMCC::AL
));
1719 BuildMI(MBB
, DebugLoc(), TII
->get(Br
.UncondBr
)).addMBB(DestBB
);
1720 BBUtils
->adjustBBSize(MBB
, TII
->getInstSizeInBytes(MBB
->back()));
1721 unsigned MaxDisp
= getUnconditionalBrDisp(Br
.UncondBr
);
1722 ImmBranches
.push_back(ImmBranch(&MBB
->back(), MaxDisp
, false, Br
.UncondBr
));
1724 // Remove the old conditional branch. It may or may not still be in MBB.
1725 BBUtils
->adjustBBSize(MI
->getParent(), -TII
->getInstSizeInBytes(*MI
));
1726 MI
->eraseFromParent();
1727 BBUtils
->adjustBBOffsetsAfter(MBB
);
1731 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1732 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1733 /// to do this if tBfar is not used.
1734 bool ARMConstantIslands::undoLRSpillRestore() {
1735 bool MadeChange
= false;
1736 for (unsigned i
= 0, e
= PushPopMIs
.size(); i
!= e
; ++i
) {
1737 MachineInstr
*MI
= PushPopMIs
[i
];
1738 // First two operands are predicates.
1739 if (MI
->getOpcode() == ARM::tPOP_RET
&&
1740 MI
->getOperand(2).getReg() == ARM::PC
&&
1741 MI
->getNumExplicitOperands() == 3) {
1742 // Create the new insn and copy the predicate from the old.
1743 BuildMI(MI
->getParent(), MI
->getDebugLoc(), TII
->get(ARM::tBX_RET
))
1744 .add(MI
->getOperand(0))
1745 .add(MI
->getOperand(1));
1746 MI
->eraseFromParent();
1748 } else if (MI
->getOpcode() == ARM::tPUSH
&&
1749 MI
->getOperand(2).getReg() == ARM::LR
&&
1750 MI
->getNumExplicitOperands() == 3) {
1751 // Just remove the push.
1752 MI
->eraseFromParent();
1759 bool ARMConstantIslands::optimizeThumb2Instructions() {
1760 bool MadeChange
= false;
1762 // Shrink ADR and LDR from constantpool.
1763 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
) {
1764 CPUser
&U
= CPUsers
[i
];
1765 unsigned Opcode
= U
.MI
->getOpcode();
1766 unsigned NewOpc
= 0;
1771 case ARM::t2LEApcrel
:
1772 if (isARMLowRegister(U
.MI
->getOperand(0).getReg())) {
1773 NewOpc
= ARM::tLEApcrel
;
1779 if (isARMLowRegister(U
.MI
->getOperand(0).getReg())) {
1780 NewOpc
= ARM::tLDRpci
;
1790 unsigned UserOffset
= getUserOffset(U
);
1791 unsigned MaxOffs
= ((1 << Bits
) - 1) * Scale
;
1793 // Be conservative with inline asm.
1794 if (!U
.KnownAlignment
)
1797 // FIXME: Check if offset is multiple of scale if scale is not 4.
1798 if (isCPEntryInRange(U
.MI
, UserOffset
, U
.CPEMI
, MaxOffs
, false, true)) {
1799 LLVM_DEBUG(dbgs() << "Shrink: " << *U
.MI
);
1800 U
.MI
->setDesc(TII
->get(NewOpc
));
1801 MachineBasicBlock
*MBB
= U
.MI
->getParent();
1802 BBUtils
->adjustBBSize(MBB
, -2);
1803 BBUtils
->adjustBBOffsetsAfter(MBB
);
1812 bool ARMConstantIslands::optimizeThumb2Branches() {
1813 bool MadeChange
= false;
1815 // The order in which branches appear in ImmBranches is approximately their
1816 // order within the function body. By visiting later branches first, we reduce
1817 // the distance between earlier forward branches and their targets, making it
1818 // more likely that the cbn?z optimization, which can only apply to forward
1819 // branches, will succeed.
1820 for (unsigned i
= ImmBranches
.size(); i
!= 0; --i
) {
1821 ImmBranch
&Br
= ImmBranches
[i
-1];
1822 unsigned Opcode
= Br
.MI
->getOpcode();
1823 unsigned NewOpc
= 0;
1840 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
1841 MachineBasicBlock
*DestBB
= Br
.MI
->getOperand(0).getMBB();
1842 if (BBUtils
->isBBInRange(Br
.MI
, DestBB
, MaxOffs
)) {
1843 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br
.MI
);
1844 Br
.MI
->setDesc(TII
->get(NewOpc
));
1845 MachineBasicBlock
*MBB
= Br
.MI
->getParent();
1846 BBUtils
->adjustBBSize(MBB
, -2);
1847 BBUtils
->adjustBBOffsetsAfter(MBB
);
1853 Opcode
= Br
.MI
->getOpcode();
1854 if (Opcode
!= ARM::tBcc
)
1857 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1858 // so this transformation is not safe.
1859 if (!Br
.MI
->killsRegister(ARM::CPSR
))
1863 unsigned PredReg
= 0;
1864 ARMCC::CondCodes Pred
= getInstrPredicate(*Br
.MI
, PredReg
);
1865 if (Pred
== ARMCC::EQ
)
1867 else if (Pred
== ARMCC::NE
)
1868 NewOpc
= ARM::tCBNZ
;
1871 MachineBasicBlock
*DestBB
= Br
.MI
->getOperand(0).getMBB();
1872 // Check if the distance is within 126. Subtract starting offset by 2
1873 // because the cmp will be eliminated.
1874 unsigned BrOffset
= BBUtils
->getOffsetOf(Br
.MI
) + 4 - 2;
1875 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1876 unsigned DestOffset
= BBInfo
[DestBB
->getNumber()].Offset
;
1877 if (BrOffset
>= DestOffset
|| (DestOffset
- BrOffset
) > 126)
1880 // Search backwards to find a tCMPi8
1881 auto *TRI
= STI
->getRegisterInfo();
1882 MachineInstr
*CmpMI
= findCMPToFoldIntoCBZ(Br
.MI
, TRI
);
1883 if (!CmpMI
|| CmpMI
->getOpcode() != ARM::tCMPi8
)
1886 Register Reg
= CmpMI
->getOperand(0).getReg();
1888 // Check for Kill flags on Reg. If they are present remove them and set kill
1890 MachineBasicBlock::iterator KillMI
= Br
.MI
;
1891 bool RegKilled
= false;
1894 if (KillMI
->killsRegister(Reg
, TRI
)) {
1895 KillMI
->clearRegisterKills(Reg
, TRI
);
1899 } while (KillMI
!= CmpMI
);
1901 // Create the new CBZ/CBNZ
1902 MachineBasicBlock
*MBB
= Br
.MI
->getParent();
1903 LLVM_DEBUG(dbgs() << "Fold: " << *CmpMI
<< " and: " << *Br
.MI
);
1904 MachineInstr
*NewBR
=
1905 BuildMI(*MBB
, Br
.MI
, Br
.MI
->getDebugLoc(), TII
->get(NewOpc
))
1906 .addReg(Reg
, getKillRegState(RegKilled
))
1907 .addMBB(DestBB
, Br
.MI
->getOperand(0).getTargetFlags());
1908 CmpMI
->eraseFromParent();
1909 Br
.MI
->eraseFromParent();
1911 BBInfo
[MBB
->getNumber()].Size
-= 2;
1912 BBUtils
->adjustBBOffsetsAfter(MBB
);
1920 static bool isSimpleIndexCalc(MachineInstr
&I
, unsigned EntryReg
,
1922 if (I
.getOpcode() != ARM::t2ADDrs
)
1925 if (I
.getOperand(0).getReg() != EntryReg
)
1928 if (I
.getOperand(1).getReg() != BaseReg
)
1931 // FIXME: what about CC and IdxReg?
1935 /// While trying to form a TBB/TBH instruction, we may (if the table
1936 /// doesn't immediately follow the BR_JT) need access to the start of the
1937 /// jump-table. We know one instruction that produces such a register; this
1938 /// function works out whether that definition can be preserved to the BR_JT,
1939 /// possibly by removing an intervening addition (which is usually needed to
1940 /// calculate the actual entry to jump to).
1941 bool ARMConstantIslands::preserveBaseRegister(MachineInstr
*JumpMI
,
1942 MachineInstr
*LEAMI
,
1945 bool &BaseRegKill
) {
1946 if (JumpMI
->getParent() != LEAMI
->getParent())
1949 // Now we hope that we have at least these instructions in the basic block:
1950 // BaseReg = t2LEA ...
1952 // EntryReg = t2ADDrs BaseReg, ...
1956 // We have to be very conservative about what we recognise here though. The
1957 // main perturbing factors to watch out for are:
1958 // + Spills at any point in the chain: not direct problems but we would
1959 // expect a blocking Def of the spilled register so in practice what we
1960 // can do is limited.
1961 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1962 // of BaseReg, but only if the t2ADDrs can be removed.
1963 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1964 // the wild, but we should be careful.
1965 Register EntryReg
= JumpMI
->getOperand(0).getReg();
1966 Register BaseReg
= LEAMI
->getOperand(0).getReg();
1968 CanDeleteLEA
= true;
1969 BaseRegKill
= false;
1970 MachineInstr
*RemovableAdd
= nullptr;
1971 MachineBasicBlock::iterator
I(LEAMI
);
1972 for (++I
; &*I
!= JumpMI
; ++I
) {
1973 if (isSimpleIndexCalc(*I
, EntryReg
, BaseReg
)) {
1978 for (unsigned K
= 0, E
= I
->getNumOperands(); K
!= E
; ++K
) {
1979 const MachineOperand
&MO
= I
->getOperand(K
);
1980 if (!MO
.isReg() || !MO
.getReg())
1982 if (MO
.isDef() && MO
.getReg() == BaseReg
)
1984 if (MO
.isUse() && MO
.getReg() == BaseReg
) {
1985 BaseRegKill
= BaseRegKill
|| MO
.isKill();
1986 CanDeleteLEA
= false;
1994 // Check the add really is removable, and that nothing else in the block
1995 // clobbers BaseReg.
1996 for (++I
; &*I
!= JumpMI
; ++I
) {
1997 for (unsigned K
= 0, E
= I
->getNumOperands(); K
!= E
; ++K
) {
1998 const MachineOperand
&MO
= I
->getOperand(K
);
1999 if (!MO
.isReg() || !MO
.getReg())
2001 if (MO
.isDef() && MO
.getReg() == BaseReg
)
2003 if (MO
.isUse() && MO
.getReg() == EntryReg
)
2004 RemovableAdd
= nullptr;
2009 RemovableAdd
->eraseFromParent();
2010 DeadSize
+= isThumb2
? 4 : 2;
2011 } else if (BaseReg
== EntryReg
) {
2012 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2017 // We reached the end of the block without seeing another definition of
2018 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2019 // used in the TBB/TBH if necessary.
2023 /// Returns whether CPEMI is the first instruction in the block
2024 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2025 /// we can switch the first register to PC and usually remove the address
2026 /// calculation that preceded it.
2027 static bool jumpTableFollowsTB(MachineInstr
*JTMI
, MachineInstr
*CPEMI
) {
2028 MachineFunction::iterator MBB
= JTMI
->getParent()->getIterator();
2029 MachineFunction
*MF
= MBB
->getParent();
2032 return MBB
!= MF
->end() && MBB
->begin() != MBB
->end() &&
2033 &*MBB
->begin() == CPEMI
;
2036 static void RemoveDeadAddBetweenLEAAndJT(MachineInstr
*LEAMI
,
2037 MachineInstr
*JumpMI
,
2038 unsigned &DeadSize
) {
2039 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2040 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2041 // and is not clobbered / used.
2042 MachineInstr
*RemovableAdd
= nullptr;
2043 Register EntryReg
= JumpMI
->getOperand(0).getReg();
2045 // Find the last ADD to set EntryReg
2046 MachineBasicBlock::iterator
I(LEAMI
);
2047 for (++I
; &*I
!= JumpMI
; ++I
) {
2048 if (I
->getOpcode() == ARM::t2ADDrs
&& I
->getOperand(0).getReg() == EntryReg
)
2055 // Ensure EntryReg is not clobbered or used.
2056 MachineBasicBlock::iterator
J(RemovableAdd
);
2057 for (++J
; &*J
!= JumpMI
; ++J
) {
2058 for (unsigned K
= 0, E
= J
->getNumOperands(); K
!= E
; ++K
) {
2059 const MachineOperand
&MO
= J
->getOperand(K
);
2060 if (!MO
.isReg() || !MO
.getReg())
2062 if (MO
.isDef() && MO
.getReg() == EntryReg
)
2064 if (MO
.isUse() && MO
.getReg() == EntryReg
)
2069 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd
);
2070 RemovableAdd
->eraseFromParent();
2074 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
2075 /// jumptables when it's possible.
2076 bool ARMConstantIslands::optimizeThumb2JumpTables() {
2077 bool MadeChange
= false;
2079 // FIXME: After the tables are shrunk, can we get rid some of the
2080 // constantpool tables?
2081 MachineJumpTableInfo
*MJTI
= MF
->getJumpTableInfo();
2082 if (!MJTI
) return false;
2084 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
2085 for (unsigned i
= 0, e
= T2JumpTables
.size(); i
!= e
; ++i
) {
2086 MachineInstr
*MI
= T2JumpTables
[i
];
2087 const MCInstrDesc
&MCID
= MI
->getDesc();
2088 unsigned NumOps
= MCID
.getNumOperands();
2089 unsigned JTOpIdx
= NumOps
- (MI
->isPredicable() ? 2 : 1);
2090 MachineOperand JTOP
= MI
->getOperand(JTOpIdx
);
2091 unsigned JTI
= JTOP
.getIndex();
2092 assert(JTI
< JT
.size());
2095 bool HalfWordOk
= true;
2096 unsigned JTOffset
= BBUtils
->getOffsetOf(MI
) + 4;
2097 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[JTI
].MBBs
;
2098 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
2099 for (unsigned j
= 0, ee
= JTBBs
.size(); j
!= ee
; ++j
) {
2100 MachineBasicBlock
*MBB
= JTBBs
[j
];
2101 unsigned DstOffset
= BBInfo
[MBB
->getNumber()].Offset
;
2102 // Negative offset is not ok. FIXME: We should change BB layout to make
2103 // sure all the branches are forward.
2104 if (ByteOk
&& (DstOffset
- JTOffset
) > ((1<<8)-1)*2)
2106 unsigned TBHLimit
= ((1<<16)-1)*2;
2107 if (HalfWordOk
&& (DstOffset
- JTOffset
) > TBHLimit
)
2109 if (!ByteOk
&& !HalfWordOk
)
2113 if (!ByteOk
&& !HalfWordOk
)
2116 CPUser
&User
= CPUsers
[JumpTableUserIndices
[JTI
]];
2117 MachineBasicBlock
*MBB
= MI
->getParent();
2118 if (!MI
->getOperand(0).isKill()) // FIXME: needed now?
2121 unsigned DeadSize
= 0;
2122 bool CanDeleteLEA
= false;
2123 bool BaseRegKill
= false;
2125 unsigned IdxReg
= ~0U;
2126 bool IdxRegKill
= true;
2128 IdxReg
= MI
->getOperand(1).getReg();
2129 IdxRegKill
= MI
->getOperand(1).isKill();
2131 bool PreservedBaseReg
=
2132 preserveBaseRegister(MI
, User
.MI
, DeadSize
, CanDeleteLEA
, BaseRegKill
);
2133 if (!jumpTableFollowsTB(MI
, User
.CPEMI
) && !PreservedBaseReg
)
2136 // We're in thumb-1 mode, so we must have something like:
2137 // %idx = tLSLri %idx, 2
2138 // %base = tLEApcrelJT
2139 // %t = tLDRr %base, %idx
2140 Register BaseReg
= User
.MI
->getOperand(0).getReg();
2142 if (User
.MI
->getIterator() == User
.MI
->getParent()->begin())
2144 MachineInstr
*Shift
= User
.MI
->getPrevNode();
2145 if (Shift
->getOpcode() != ARM::tLSLri
||
2146 Shift
->getOperand(3).getImm() != 2 ||
2147 !Shift
->getOperand(2).isKill())
2149 IdxReg
= Shift
->getOperand(2).getReg();
2150 Register ShiftedIdxReg
= Shift
->getOperand(0).getReg();
2152 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2153 // the range is checked later, but the LEA might still clobber it and not
2154 // actually get removed.
2155 if (BaseReg
== IdxReg
&& !jumpTableFollowsTB(MI
, User
.CPEMI
))
2158 MachineInstr
*Load
= User
.MI
->getNextNode();
2159 if (Load
->getOpcode() != ARM::tLDRr
)
2161 if (Load
->getOperand(1).getReg() != BaseReg
||
2162 Load
->getOperand(2).getReg() != ShiftedIdxReg
||
2163 !Load
->getOperand(2).isKill())
2166 // If we're in PIC mode, there should be another ADD following.
2167 auto *TRI
= STI
->getRegisterInfo();
2169 // %base cannot be redefined after the load as it will appear before
2174 if (registerDefinedBetween(BaseReg
, Load
->getNextNode(), MBB
->end(), TRI
))
2177 if (isPositionIndependentOrROPI
) {
2178 MachineInstr
*Add
= Load
->getNextNode();
2179 if (Add
->getOpcode() != ARM::tADDrr
||
2180 Add
->getOperand(2).getReg() != BaseReg
||
2181 Add
->getOperand(3).getReg() != Load
->getOperand(0).getReg() ||
2182 !Add
->getOperand(3).isKill())
2184 if (Add
->getOperand(0).getReg() != MI
->getOperand(0).getReg())
2186 if (registerDefinedBetween(IdxReg
, Add
->getNextNode(), MI
, TRI
))
2187 // IdxReg gets redefined in the middle of the sequence.
2189 Add
->eraseFromParent();
2192 if (Load
->getOperand(0).getReg() != MI
->getOperand(0).getReg())
2194 if (registerDefinedBetween(IdxReg
, Load
->getNextNode(), MI
, TRI
))
2195 // IdxReg gets redefined in the middle of the sequence.
2199 // Now safe to delete the load and lsl. The LEA will be removed later.
2200 CanDeleteLEA
= true;
2201 Shift
->eraseFromParent();
2202 Load
->eraseFromParent();
2206 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI
);
2207 MachineInstr
*CPEMI
= User
.CPEMI
;
2208 unsigned Opc
= ByteOk
? ARM::t2TBB_JT
: ARM::t2TBH_JT
;
2210 Opc
= ByteOk
? ARM::tTBB_JT
: ARM::tTBH_JT
;
2212 MachineBasicBlock::iterator MI_JT
= MI
;
2213 MachineInstr
*NewJTMI
=
2214 BuildMI(*MBB
, MI_JT
, MI
->getDebugLoc(), TII
->get(Opc
))
2215 .addReg(User
.MI
->getOperand(0).getReg(),
2216 getKillRegState(BaseRegKill
))
2217 .addReg(IdxReg
, getKillRegState(IdxRegKill
))
2218 .addJumpTableIndex(JTI
, JTOP
.getTargetFlags())
2219 .addImm(CPEMI
->getOperand(0).getImm());
2220 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << ": " << *NewJTMI
);
2222 unsigned JTOpc
= ByteOk
? ARM::JUMPTABLE_TBB
: ARM::JUMPTABLE_TBH
;
2223 CPEMI
->setDesc(TII
->get(JTOpc
));
2225 if (jumpTableFollowsTB(MI
, User
.CPEMI
)) {
2226 NewJTMI
->getOperand(0).setReg(ARM::PC
);
2227 NewJTMI
->getOperand(0).setIsKill(false);
2231 RemoveDeadAddBetweenLEAAndJT(User
.MI
, MI
, DeadSize
);
2233 User
.MI
->eraseFromParent();
2234 DeadSize
+= isThumb2
? 4 : 2;
2236 // The LEA was eliminated, the TBB instruction becomes the only new user
2237 // of the jump table.
2241 User
.IsSoImm
= false;
2242 User
.KnownAlignment
= false;
2244 // The LEA couldn't be eliminated, so we must add another CPUser to
2245 // record the TBB or TBH use.
2246 int CPEntryIdx
= JumpTableEntryIndices
[JTI
];
2247 auto &CPEs
= CPEntries
[CPEntryIdx
];
2249 find_if(CPEs
, [&](CPEntry
&E
) { return E
.CPEMI
== User
.CPEMI
; });
2251 CPUsers
.emplace_back(CPUser(NewJTMI
, User
.CPEMI
, 4, false, false));
2255 unsigned NewSize
= TII
->getInstSizeInBytes(*NewJTMI
);
2256 unsigned OrigSize
= TII
->getInstSizeInBytes(*MI
);
2257 MI
->eraseFromParent();
2259 int Delta
= OrigSize
- NewSize
+ DeadSize
;
2260 BBInfo
[MBB
->getNumber()].Size
-= Delta
;
2261 BBUtils
->adjustBBOffsetsAfter(MBB
);
2270 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2271 /// jump tables always branch forwards, since that's what tbb and tbh need.
2272 bool ARMConstantIslands::reorderThumb2JumpTables() {
2273 bool MadeChange
= false;
2275 MachineJumpTableInfo
*MJTI
= MF
->getJumpTableInfo();
2276 if (!MJTI
) return false;
2278 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
2279 for (unsigned i
= 0, e
= T2JumpTables
.size(); i
!= e
; ++i
) {
2280 MachineInstr
*MI
= T2JumpTables
[i
];
2281 const MCInstrDesc
&MCID
= MI
->getDesc();
2282 unsigned NumOps
= MCID
.getNumOperands();
2283 unsigned JTOpIdx
= NumOps
- (MI
->isPredicable() ? 2 : 1);
2284 MachineOperand JTOP
= MI
->getOperand(JTOpIdx
);
2285 unsigned JTI
= JTOP
.getIndex();
2286 assert(JTI
< JT
.size());
2288 // We prefer if target blocks for the jump table come after the jump
2289 // instruction so we can use TB[BH]. Loop through the target blocks
2290 // and try to adjust them such that that's true.
2291 int JTNumber
= MI
->getParent()->getNumber();
2292 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[JTI
].MBBs
;
2293 for (unsigned j
= 0, ee
= JTBBs
.size(); j
!= ee
; ++j
) {
2294 MachineBasicBlock
*MBB
= JTBBs
[j
];
2295 int DTNumber
= MBB
->getNumber();
2297 if (DTNumber
< JTNumber
) {
2298 // The destination precedes the switch. Try to move the block forward
2299 // so we have a positive offset.
2300 MachineBasicBlock
*NewBB
=
2301 adjustJTTargetBlockForward(MBB
, MI
->getParent());
2303 MJTI
->ReplaceMBBInJumpTable(JTI
, JTBBs
[j
], NewBB
);
2312 MachineBasicBlock
*ARMConstantIslands::
2313 adjustJTTargetBlockForward(MachineBasicBlock
*BB
, MachineBasicBlock
*JTBB
) {
2314 // If the destination block is terminated by an unconditional branch,
2315 // try to move it; otherwise, create a new block following the jump
2316 // table that branches back to the actual target. This is a very simple
2317 // heuristic. FIXME: We can definitely improve it.
2318 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
2319 SmallVector
<MachineOperand
, 4> Cond
;
2320 SmallVector
<MachineOperand
, 4> CondPrior
;
2321 MachineFunction::iterator BBi
= BB
->getIterator();
2322 MachineFunction::iterator OldPrior
= std::prev(BBi
);
2324 // If the block terminator isn't analyzable, don't try to move the block
2325 bool B
= TII
->analyzeBranch(*BB
, TBB
, FBB
, Cond
);
2327 // If the block ends in an unconditional branch, move it. The prior block
2328 // has to have an analyzable terminator for us to move this one. Be paranoid
2329 // and make sure we're not trying to move the entry block of the function.
2330 if (!B
&& Cond
.empty() && BB
!= &MF
->front() &&
2331 !TII
->analyzeBranch(*OldPrior
, TBB
, FBB
, CondPrior
)) {
2332 BB
->moveAfter(JTBB
);
2333 OldPrior
->updateTerminator();
2334 BB
->updateTerminator();
2335 // Update numbering to account for the block being moved.
2336 MF
->RenumberBlocks();
2341 // Create a new MBB for the code after the jump BB.
2342 MachineBasicBlock
*NewBB
=
2343 MF
->CreateMachineBasicBlock(JTBB
->getBasicBlock());
2344 MachineFunction::iterator MBBI
= ++JTBB
->getIterator();
2345 MF
->insert(MBBI
, NewBB
);
2347 // Copy live-in information to new block.
2348 for (const MachineBasicBlock::RegisterMaskPair
&RegMaskPair
: BB
->liveins())
2349 NewBB
->addLiveIn(RegMaskPair
);
2351 // Add an unconditional branch from NewBB to BB.
2352 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2353 // correspond directly to anything in the source.
2355 BuildMI(NewBB
, DebugLoc(), TII
->get(ARM::t2B
))
2357 .add(predOps(ARMCC::AL
));
2359 BuildMI(NewBB
, DebugLoc(), TII
->get(ARM::tB
))
2361 .add(predOps(ARMCC::AL
));
2363 // Update internal data structures to account for the newly inserted MBB.
2364 MF
->RenumberBlocks(NewBB
);
2367 NewBB
->addSuccessor(BB
);
2368 JTBB
->replaceSuccessor(BB
, NewBB
);
2374 /// createARMConstantIslandPass - returns an instance of the constpool
2376 FunctionPass
*llvm::createARMConstantIslandPass() {
2377 return new ARMConstantIslands();
2380 INITIALIZE_PASS(ARMConstantIslands
, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME
,