1 //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARM.h"
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/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineJumpTableInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/MC/MCInstrDesc.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstdint>
54 #include <iterator>
55 #include <utility>
56 #include <vector>
57 
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "arm-cp-islands"
61 
62 #define ARM_CP_ISLANDS_OPT_NAME \
63   "ARM constant island placement and branch shortening pass"
64 STATISTIC(NumCPEs,       "Number of constpool entries");
65 STATISTIC(NumSplit,      "Number of uncond branches inserted");
66 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
67 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
68 STATISTIC(NumTBs,        "Number of table branches generated");
69 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
70 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
71 STATISTIC(NumCBZ,        "Number of CBZ / CBNZ formed");
72 STATISTIC(NumJTMoved,    "Number of jump table destination blocks moved");
73 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
74 STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");
75 
76 static cl::opt<bool>
77 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
78           cl::desc("Adjust basic block layout to better use TB[BH]"));
79 
80 static cl::opt<unsigned>
81 CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
82           cl::desc("The max number of iteration for converge"));
83 
84 static cl::opt<bool> SynthesizeThumb1TBB(
85     "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
86     cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
87              "equivalent to the TBB/TBH instructions"));
88 
89 namespace {
90 
91   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
92   /// requires constant pool entries to be scattered among the instructions
93   /// inside a function.  To do this, it completely ignores the normal LLVM
94   /// constant pool; instead, it places constants wherever it feels like with
95   /// special instructions.
96   ///
97   /// The terminology used in this pass includes:
98   ///   Islands - Clumps of constants placed in the function.
99   ///   Water   - Potential places where an island could be formed.
100   ///   CPE     - A constant pool entry that has been placed somewhere, which
101   ///             tracks a list of users.
102   class ARMConstantIslands : public MachineFunctionPass {
103     std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
104 
105     /// WaterList - A sorted list of basic blocks where islands could be placed
106     /// (i.e. blocks that don't fall through to the following block, due
107     /// to a return, unreachable, or unconditional branch).
108     std::vector<MachineBasicBlock*> WaterList;
109 
110     /// NewWaterList - The subset of WaterList that was created since the
111     /// previous iteration by inserting unconditional branches.
112     SmallSet<MachineBasicBlock*, 4> NewWaterList;
113 
114     using water_iterator = std::vector<MachineBasicBlock *>::iterator;
115 
116     /// CPUser - One user of a constant pool, keeping the machine instruction
117     /// pointer, the constant pool being referenced, and the max displacement
118     /// allowed from the instruction to the CP.  The HighWaterMark records the
119     /// highest basic block where a new CPEntry can be placed.  To ensure this
120     /// pass terminates, the CP entries are initially placed at the end of the
121     /// function and then move monotonically to lower addresses.  The
122     /// exception to this rule is when the current CP entry for a particular
123     /// CPUser is out of range, but there is another CP entry for the same
124     /// constant value in range.  We want to use the existing in-range CP
125     /// entry, but if it later moves out of range, the search for new water
126     /// should resume where it left off.  The HighWaterMark is used to record
127     /// that point.
128     struct CPUser {
129       MachineInstr *MI;
130       MachineInstr *CPEMI;
131       MachineBasicBlock *HighWaterMark;
132       unsigned MaxDisp;
133       bool NegOk;
134       bool IsSoImm;
135       bool KnownAlignment = false;
136 
137       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
138              bool neg, bool soimm)
139         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
140         HighWaterMark = CPEMI->getParent();
141       }
142 
143       /// getMaxDisp - Returns the maximum displacement supported by MI.
144       /// Correct for unknown alignment.
145       /// Conservatively subtract 2 bytes to handle weird alignment effects.
146       unsigned getMaxDisp() const {
147         return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
148       }
149     };
150 
151     /// CPUsers - Keep track of all of the machine instructions that use various
152     /// constant pools and their max displacement.
153     std::vector<CPUser> CPUsers;
154 
155     /// CPEntry - One per constant pool entry, keeping the machine instruction
156     /// pointer, the constpool index, and the number of CPUser's which
157     /// reference this entry.
158     struct CPEntry {
159       MachineInstr *CPEMI;
160       unsigned CPI;
161       unsigned RefCount;
162 
163       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
164         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
165     };
166 
167     /// CPEntries - Keep track of all of the constant pool entry machine
168     /// instructions. For each original constpool index (i.e. those that existed
169     /// upon entry to this pass), it keeps a vector of entries.  Original
170     /// elements are cloned as we go along; the clones are put in the vector of
171     /// the original element, but have distinct CPIs.
172     ///
173     /// The first half of CPEntries contains generic constants, the second half
174     /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
175     /// which vector it will be in here.
176     std::vector<std::vector<CPEntry>> CPEntries;
177 
178     /// Maps a JT index to the offset in CPEntries containing copies of that
179     /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
180     DenseMap<int, int> JumpTableEntryIndices;
181 
182     /// Maps a JT index to the LEA that actually uses the index to calculate its
183     /// base address.
184     DenseMap<int, int> JumpTableUserIndices;
185 
186     /// ImmBranch - One per immediate branch, keeping the machine instruction
187     /// pointer, conditional or unconditional, the max displacement,
188     /// and (if isCond is true) the corresponding unconditional branch
189     /// opcode.
190     struct ImmBranch {
191       MachineInstr *MI;
192       unsigned MaxDisp : 31;
193       bool isCond : 1;
194       unsigned UncondBr;
195 
196       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
197         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
198     };
199 
200     /// ImmBranches - Keep track of all the immediate branch instructions.
201     std::vector<ImmBranch> ImmBranches;
202 
203     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
204     SmallVector<MachineInstr*, 4> PushPopMIs;
205 
206     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
207     SmallVector<MachineInstr*, 4> T2JumpTables;
208 
209     /// HasFarJump - True if any far jump instruction has been emitted during
210     /// the branch fix up pass.
211     bool HasFarJump;
212 
213     MachineFunction *MF;
214     MachineConstantPool *MCP;
215     const ARMBaseInstrInfo *TII;
216     const ARMSubtarget *STI;
217     ARMFunctionInfo *AFI;
218     MachineDominatorTree *DT = nullptr;
219     bool isThumb;
220     bool isThumb1;
221     bool isThumb2;
222     bool isPositionIndependentOrROPI;
223 
224   public:
225     static char ID;
226 
227     ARMConstantIslands() : MachineFunctionPass(ID) {}
228 
229     bool runOnMachineFunction(MachineFunction &MF) override;
230 
231     void getAnalysisUsage(AnalysisUsage &AU) const override {
232       AU.addRequired<MachineDominatorTree>();
233       MachineFunctionPass::getAnalysisUsage(AU);
234     }
235 
236     MachineFunctionProperties getRequiredProperties() const override {
237       return MachineFunctionProperties().set(
238           MachineFunctionProperties::Property::NoVRegs);
239     }
240 
241     StringRef getPassName() const override {
242       return ARM_CP_ISLANDS_OPT_NAME;
243     }
244 
245   private:
246     void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
247     void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
248     bool BBHasFallthrough(MachineBasicBlock *MBB);
249     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
250     unsigned getCPELogAlign(const MachineInstr *CPEMI);
251     void scanFunctionJumpTables();
252     void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
253     MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
254     void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
255     bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
256     unsigned getCombinedIndex(const MachineInstr *CPEMI);
257     int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
258     bool findAvailableWater(CPUser&U, unsigned UserOffset,
259                             water_iterator &WaterIter, bool CloserWater);
260     void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
261                         MachineBasicBlock *&NewMBB);
262     bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
263     void removeDeadCPEMI(MachineInstr *CPEMI);
264     bool removeUnusedCPEntries();
265     bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
266                           MachineInstr *CPEMI, unsigned Disp, bool NegOk,
267                           bool DoDump = false);
268     bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
269                         CPUser &U, unsigned &Growth);
270     bool fixupImmediateBr(ImmBranch &Br);
271     bool fixupConditionalBr(ImmBranch &Br);
272     bool fixupUnconditionalBr(ImmBranch &Br);
273     bool undoLRSpillRestore();
274     bool optimizeThumb2Instructions();
275     bool optimizeThumb2Branches();
276     bool reorderThumb2JumpTables();
277     bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
278                               unsigned &DeadSize, bool &CanDeleteLEA,
279                               bool &BaseRegKill);
280     bool optimizeThumb2JumpTables();
281     MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
282                                                   MachineBasicBlock *JTBB);
283 
284     unsigned getUserOffset(CPUser&) const;
285     void dumpBBs();
286     void verify();
287 
288     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
289                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
290     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
291                          const CPUser &U) {
292       return isOffsetInRange(UserOffset, TrialOffset,
293                              U.getMaxDisp(), U.NegOk, U.IsSoImm);
294     }
295   };
296 
297 } // end anonymous namespace
298 
299 char ARMConstantIslands::ID = 0;
300 
301 /// verify - check BBOffsets, BBSizes, alignment of islands
302 void ARMConstantIslands::verify() {
303 #ifndef NDEBUG
304   BBInfoVector &BBInfo = BBUtils->getBBInfo();
305   assert(std::is_sorted(MF->begin(), MF->end(),
306                         [&BBInfo](const MachineBasicBlock &LHS,
307                                   const MachineBasicBlock &RHS) {
308                           return BBInfo[LHS.getNumber()].postOffset() <
309                                  BBInfo[RHS.getNumber()].postOffset();
310                         }));
311   LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
312   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
313     CPUser &U = CPUsers[i];
314     unsigned UserOffset = getUserOffset(U);
315     // Verify offset using the real max displacement without the safety
316     // adjustment.
317     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
318                          /* DoDump = */ true)) {
319       LLVM_DEBUG(dbgs() << "OK\n");
320       continue;
321     }
322     LLVM_DEBUG(dbgs() << "Out of range.\n");
323     dumpBBs();
324     LLVM_DEBUG(MF->dump());
325     llvm_unreachable("Constant pool entry out of range!");
326   }
327 #endif
328 }
329 
330 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
331 /// print block size and offset information - debugging
332 LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
333   BBInfoVector &BBInfo = BBUtils->getBBInfo();
334   LLVM_DEBUG({
335     for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
336       const BasicBlockInfo &BBI = BBInfo[J];
337       dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
338              << " kb=" << unsigned(BBI.KnownBits)
339              << " ua=" << unsigned(BBI.Unalign)
340              << " pa=" << unsigned(BBI.PostAlign)
341              << format(" size=%#x\n", BBInfo[J].Size);
342     }
343   });
344 }
345 #endif
346 
347 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
348   MF = &mf;
349   MCP = mf.getConstantPool();
350   BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf));
351 
352   LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
353                     << MCP->getConstants().size() << " CP entries, aligned to "
354                     << MCP->getConstantPoolAlignment() << " bytes *****\n");
355 
356   STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
357   TII = STI->getInstrInfo();
358   isPositionIndependentOrROPI =
359       STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
360   AFI = MF->getInfo<ARMFunctionInfo>();
361   DT = &getAnalysis<MachineDominatorTree>();
362 
363   isThumb = AFI->isThumbFunction();
364   isThumb1 = AFI->isThumb1OnlyFunction();
365   isThumb2 = AFI->isThumb2Function();
366 
367   HasFarJump = false;
368   bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
369 
370   // Renumber all of the machine basic blocks in the function, guaranteeing that
371   // the numbers agree with the position of the block in the function.
372   MF->RenumberBlocks();
373 
374   // Try to reorder and otherwise adjust the block layout to make good use
375   // of the TB[BH] instructions.
376   bool MadeChange = false;
377   if (GenerateTBB && AdjustJumpTableBlocks) {
378     scanFunctionJumpTables();
379     MadeChange |= reorderThumb2JumpTables();
380     // Data is out of date, so clear it. It'll be re-computed later.
381     T2JumpTables.clear();
382     // Blocks may have shifted around. Keep the numbering up to date.
383     MF->RenumberBlocks();
384   }
385 
386   // Perform the initial placement of the constant pool entries.  To start with,
387   // we put them all at the end of the function.
388   std::vector<MachineInstr*> CPEMIs;
389   if (!MCP->isEmpty())
390     doInitialConstPlacement(CPEMIs);
391 
392   if (MF->getJumpTableInfo())
393     doInitialJumpTablePlacement(CPEMIs);
394 
395   /// The next UID to take is the first unused one.
396   AFI->initPICLabelUId(CPEMIs.size());
397 
398   // Do the initial scan of the function, building up information about the
399   // sizes of each block, the location of all the water, and finding all of the
400   // constant pool users.
401   initializeFunctionInfo(CPEMIs);
402   CPEMIs.clear();
403   LLVM_DEBUG(dumpBBs());
404 
405   // Functions with jump tables need an alignment of 4 because they use the ADR
406   // instruction, which aligns the PC to 4 bytes before adding an offset.
407   if (!T2JumpTables.empty())
408     MF->ensureAlignment(llvm::Align(4));
409 
410   /// Remove dead constant pool entries.
411   MadeChange |= removeUnusedCPEntries();
412 
413   // Iteratively place constant pool entries and fix up branches until there
414   // is no change.
415   unsigned NoCPIters = 0, NoBRIters = 0;
416   while (true) {
417     LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
418     bool CPChange = false;
419     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
420       // For most inputs, it converges in no more than 5 iterations.
421       // If it doesn't end in 10, the input may have huge BB or many CPEs.
422       // In this case, we will try different heuristics.
423       CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
424     if (CPChange && ++NoCPIters > CPMaxIteration)
425       report_fatal_error("Constant Island pass failed to converge!");
426     LLVM_DEBUG(dumpBBs());
427 
428     // Clear NewWaterList now.  If we split a block for branches, it should
429     // appear as "new water" for the next iteration of constant pool placement.
430     NewWaterList.clear();
431 
432     LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
433     bool BRChange = false;
434     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
435       BRChange |= fixupImmediateBr(ImmBranches[i]);
436     if (BRChange && ++NoBRIters > 30)
437       report_fatal_error("Branch Fix Up pass failed to converge!");
438     LLVM_DEBUG(dumpBBs());
439 
440     if (!CPChange && !BRChange)
441       break;
442     MadeChange = true;
443   }
444 
445   // Shrink 32-bit Thumb2 load and store instructions.
446   if (isThumb2 && !STI->prefers32BitThumb())
447     MadeChange |= optimizeThumb2Instructions();
448 
449   // Shrink 32-bit branch instructions.
450   if (isThumb && STI->hasV8MBaselineOps())
451     MadeChange |= optimizeThumb2Branches();
452 
453   // Optimize jump tables using TBB / TBH.
454   if (GenerateTBB && !STI->genExecuteOnly())
455     MadeChange |= optimizeThumb2JumpTables();
456 
457   // After a while, this might be made debug-only, but it is not expensive.
458   verify();
459 
460   // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
461   // undo the spill / restore of LR if possible.
462   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
463     MadeChange |= undoLRSpillRestore();
464 
465   // Save the mapping between original and cloned constpool entries.
466   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
467     for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
468       const CPEntry & CPE = CPEntries[i][j];
469       if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
470         AFI->recordCPEClone(i, CPE.CPI);
471     }
472   }
473 
474   LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
475 
476   BBUtils->clear();
477   WaterList.clear();
478   CPUsers.clear();
479   CPEntries.clear();
480   JumpTableEntryIndices.clear();
481   JumpTableUserIndices.clear();
482   ImmBranches.clear();
483   PushPopMIs.clear();
484   T2JumpTables.clear();
485 
486   return MadeChange;
487 }
488 
489 /// Perform the initial placement of the regular constant pool entries.
490 /// To start with, we put them all at the end of the function.
491 void
492 ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
493   // Create the basic block to hold the CPE's.
494   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
495   MF->push_back(BB);
496 
497   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
498   unsigned MaxLogAlign = Log2_32(MCP->getConstantPoolAlignment());
499 
500   // Mark the basic block as required by the const-pool.
501   BB->setLogAlignment(MaxLogAlign);
502 
503   // The function needs to be as aligned as the basic blocks. The linker may
504   // move functions around based on their alignment.
505   MF->ensureAlignment(BB->getAlignment());
506 
507   // Order the entries in BB by descending alignment.  That ensures correct
508   // alignment of all entries as long as BB is sufficiently aligned.  Keep
509   // track of the insertion point for each alignment.  We are going to bucket
510   // sort the entries as they are created.
511   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
512                                                        BB->end());
513 
514   // Add all of the constants from the constant pool to the end block, use an
515   // identity mapping of CPI's to CPE's.
516   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
517 
518   const DataLayout &TD = MF->getDataLayout();
519   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
520     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
521     unsigned Align = CPs[i].getAlignment();
522     assert(isPowerOf2_32(Align) && "Invalid alignment");
523     // Verify that all constant pool entries are a multiple of their alignment.
524     // If not, we would have to pad them out so that instructions stay aligned.
525     assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
526 
527     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
528     unsigned LogAlign = Log2_32(Align);
529     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
530     MachineInstr *CPEMI =
531       BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
532         .addImm(i).addConstantPoolIndex(i).addImm(Size);
533     CPEMIs.push_back(CPEMI);
534 
535     // Ensure that future entries with higher alignment get inserted before
536     // CPEMI. This is bucket sort with iterators.
537     for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
538       if (InsPoint[a] == InsAt)
539         InsPoint[a] = CPEMI;
540 
541     // Add a new CPEntry, but no corresponding CPUser yet.
542     CPEntries.emplace_back(1, CPEntry(CPEMI, i));
543     ++NumCPEs;
544     LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
545                       << Size << ", align = " << Align << '\n');
546   }
547   LLVM_DEBUG(BB->dump());
548 }
549 
550 /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
551 /// instructions can be made more efficient if the jump table immediately
552 /// follows the instruction, it's best to place them immediately next to their
553 /// jumps to begin with. In almost all cases they'll never be moved from that
554 /// position.
555 void ARMConstantIslands::doInitialJumpTablePlacement(
556     std::vector<MachineInstr *> &CPEMIs) {
557   unsigned i = CPEntries.size();
558   auto MJTI = MF->getJumpTableInfo();
559   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
560 
561   MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
562   for (MachineBasicBlock &MBB : *MF) {
563     auto MI = MBB.getLastNonDebugInstr();
564     if (MI == MBB.end())
565       continue;
566 
567     unsigned JTOpcode;
568     switch (MI->getOpcode()) {
569     default:
570       continue;
571     case ARM::BR_JTadd:
572     case ARM::BR_JTr:
573     case ARM::tBR_JTr:
574     case ARM::BR_JTm_i12:
575     case ARM::BR_JTm_rs:
576       JTOpcode = ARM::JUMPTABLE_ADDRS;
577       break;
578     case ARM::t2BR_JT:
579       JTOpcode = ARM::JUMPTABLE_INSTS;
580       break;
581     case ARM::tTBB_JT:
582     case ARM::t2TBB_JT:
583       JTOpcode = ARM::JUMPTABLE_TBB;
584       break;
585     case ARM::tTBH_JT:
586     case ARM::t2TBH_JT:
587       JTOpcode = ARM::JUMPTABLE_TBH;
588       break;
589     }
590 
591     unsigned NumOps = MI->getDesc().getNumOperands();
592     MachineOperand JTOp =
593       MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
594     unsigned JTI = JTOp.getIndex();
595     unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
596     MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
597     MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
598     MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
599                                   DebugLoc(), TII->get(JTOpcode))
600                               .addImm(i++)
601                               .addJumpTableIndex(JTI)
602                               .addImm(Size);
603     CPEMIs.push_back(CPEMI);
604     CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
605     JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
606     if (!LastCorrectlyNumberedBB)
607       LastCorrectlyNumberedBB = &MBB;
608   }
609 
610   // If we did anything then we need to renumber the subsequent blocks.
611   if (LastCorrectlyNumberedBB)
612     MF->RenumberBlocks(LastCorrectlyNumberedBB);
613 }
614 
615 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
616 /// into the block immediately after it.
617 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
618   // Get the next machine basic block in the function.
619   MachineFunction::iterator MBBI = MBB->getIterator();
620   // Can't fall off end of function.
621   if (std::next(MBBI) == MBB->getParent()->end())
622     return false;
623 
624   MachineBasicBlock *NextBB = &*std::next(MBBI);
625   if (!MBB->isSuccessor(NextBB))
626     return false;
627 
628   // Try to analyze the end of the block. A potential fallthrough may already
629   // have an unconditional branch for whatever reason.
630   MachineBasicBlock *TBB, *FBB;
631   SmallVector<MachineOperand, 4> Cond;
632   bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
633   return TooDifficult || FBB == nullptr;
634 }
635 
636 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
637 /// look up the corresponding CPEntry.
638 ARMConstantIslands::CPEntry *
639 ARMConstantIslands::findConstPoolEntry(unsigned CPI,
640                                        const MachineInstr *CPEMI) {
641   std::vector<CPEntry> &CPEs = CPEntries[CPI];
642   // Number of entries per constpool index should be small, just do a
643   // linear search.
644   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
645     if (CPEs[i].CPEMI == CPEMI)
646       return &CPEs[i];
647   }
648   return nullptr;
649 }
650 
651 /// getCPELogAlign - Returns the required alignment of the constant pool entry
652 /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
653 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
654   switch (CPEMI->getOpcode()) {
655   case ARM::CONSTPOOL_ENTRY:
656     break;
657   case ARM::JUMPTABLE_TBB:
658     return isThumb1 ? 2 : 0;
659   case ARM::JUMPTABLE_TBH:
660     return isThumb1 ? 2 : 1;
661   case ARM::JUMPTABLE_INSTS:
662     return 1;
663   case ARM::JUMPTABLE_ADDRS:
664     return 2;
665   default:
666     llvm_unreachable("unknown constpool entry kind");
667   }
668 
669   unsigned CPI = getCombinedIndex(CPEMI);
670   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
671   unsigned Align = MCP->getConstants()[CPI].getAlignment();
672   assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
673   return Log2_32(Align);
674 }
675 
676 /// scanFunctionJumpTables - Do a scan of the function, building up
677 /// information about the sizes of each block and the locations of all
678 /// the jump tables.
679 void ARMConstantIslands::scanFunctionJumpTables() {
680   for (MachineBasicBlock &MBB : *MF) {
681     for (MachineInstr &I : MBB)
682       if (I.isBranch() &&
683           (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
684         T2JumpTables.push_back(&I);
685   }
686 }
687 
688 /// initializeFunctionInfo - Do the initial scan of the function, building up
689 /// information about the sizes of each block, the location of all the water,
690 /// and finding all of the constant pool users.
691 void ARMConstantIslands::
692 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
693 
694   BBUtils->computeAllBlockSizes();
695   BBInfoVector &BBInfo = BBUtils->getBBInfo();
696   // The known bits of the entry block offset are determined by the function
697   // alignment.
698   BBInfo.front().KnownBits = Log2(MF->getAlignment());
699 
700   // Compute block offsets and known bits.
701   BBUtils->adjustBBOffsetsAfter(&MF->front());
702 
703   // Now go back through the instructions and build up our data structures.
704   for (MachineBasicBlock &MBB : *MF) {
705     // If this block doesn't fall through into the next MBB, then this is
706     // 'water' that a constant pool island could be placed.
707     if (!BBHasFallthrough(&MBB))
708       WaterList.push_back(&MBB);
709 
710     for (MachineInstr &I : MBB) {
711       if (I.isDebugInstr())
712         continue;
713 
714       unsigned Opc = I.getOpcode();
715       if (I.isBranch()) {
716         bool isCond = false;
717         unsigned Bits = 0;
718         unsigned Scale = 1;
719         int UOpc = Opc;
720         switch (Opc) {
721         default:
722           continue;  // Ignore other JT branches
723         case ARM::t2BR_JT:
724         case ARM::tBR_JTr:
725           T2JumpTables.push_back(&I);
726           continue;   // Does not get an entry in ImmBranches
727         case ARM::Bcc:
728           isCond = true;
729           UOpc = ARM::B;
730           LLVM_FALLTHROUGH;
731         case ARM::B:
732           Bits = 24;
733           Scale = 4;
734           break;
735         case ARM::tBcc:
736           isCond = true;
737           UOpc = ARM::tB;
738           Bits = 8;
739           Scale = 2;
740           break;
741         case ARM::tB:
742           Bits = 11;
743           Scale = 2;
744           break;
745         case ARM::t2Bcc:
746           isCond = true;
747           UOpc = ARM::t2B;
748           Bits = 20;
749           Scale = 2;
750           break;
751         case ARM::t2B:
752           Bits = 24;
753           Scale = 2;
754           break;
755         }
756 
757         // Record this immediate branch.
758         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
759         ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
760       }
761 
762       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
763         PushPopMIs.push_back(&I);
764 
765       if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
766           Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
767           Opc == ARM::JUMPTABLE_TBH)
768         continue;
769 
770       // Scan the instructions for constant pool operands.
771       for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
772         if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
773           // We found one.  The addressing mode tells us the max displacement
774           // from the PC that this instruction permits.
775 
776           // Basic size info comes from the TSFlags field.
777           unsigned Bits = 0;
778           unsigned Scale = 1;
779           bool NegOk = false;
780           bool IsSoImm = false;
781 
782           switch (Opc) {
783           default:
784             llvm_unreachable("Unknown addressing mode for CP reference!");
785 
786           // Taking the address of a CP entry.
787           case ARM::LEApcrel:
788           case ARM::LEApcrelJT:
789             // This takes a SoImm, which is 8 bit immediate rotated. We'll
790             // pretend the maximum offset is 255 * 4. Since each instruction
791             // 4 byte wide, this is always correct. We'll check for other
792             // displacements that fits in a SoImm as well.
793             Bits = 8;
794             Scale = 4;
795             NegOk = true;
796             IsSoImm = true;
797             break;
798           case ARM::t2LEApcrel:
799           case ARM::t2LEApcrelJT:
800             Bits = 12;
801             NegOk = true;
802             break;
803           case ARM::tLEApcrel:
804           case ARM::tLEApcrelJT:
805             Bits = 8;
806             Scale = 4;
807             break;
808 
809           case ARM::LDRBi12:
810           case ARM::LDRi12:
811           case ARM::LDRcp:
812           case ARM::t2LDRpci:
813           case ARM::t2LDRHpci:
814           case ARM::t2LDRBpci:
815             Bits = 12;  // +-offset_12
816             NegOk = true;
817             break;
818 
819           case ARM::tLDRpci:
820             Bits = 8;
821             Scale = 4;  // +(offset_8*4)
822             break;
823 
824           case ARM::VLDRD:
825           case ARM::VLDRS:
826             Bits = 8;
827             Scale = 4;  // +-(offset_8*4)
828             NegOk = true;
829             break;
830           case ARM::VLDRH:
831             Bits = 8;
832             Scale = 2;  // +-(offset_8*2)
833             NegOk = true;
834             break;
835           }
836 
837           // Remember that this is a user of a CP entry.
838           unsigned CPI = I.getOperand(op).getIndex();
839           if (I.getOperand(op).isJTI()) {
840             JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
841             CPI = JumpTableEntryIndices[CPI];
842           }
843 
844           MachineInstr *CPEMI = CPEMIs[CPI];
845           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
846           CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
847 
848           // Increment corresponding CPEntry reference count.
849           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
850           assert(CPE && "Cannot find a corresponding CPEntry!");
851           CPE->RefCount++;
852 
853           // Instructions can only use one CP entry, don't bother scanning the
854           // rest of the operands.
855           break;
856         }
857     }
858   }
859 }
860 
861 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
862 /// ID.
863 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
864                               const MachineBasicBlock *RHS) {
865   return LHS->getNumber() < RHS->getNumber();
866 }
867 
868 /// updateForInsertedWaterBlock - When a block is newly inserted into the
869 /// machine function, it upsets all of the block numbers.  Renumber the blocks
870 /// and update the arrays that parallel this numbering.
871 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
872   // Renumber the MBB's to keep them consecutive.
873   NewBB->getParent()->RenumberBlocks(NewBB);
874 
875   // Insert an entry into BBInfo to align it properly with the (newly
876   // renumbered) block numbers.
877   BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
878 
879   // Next, update WaterList.  Specifically, we need to add NewMBB as having
880   // available water after it.
881   water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
882   WaterList.insert(IP, NewBB);
883 }
884 
885 /// Split the basic block containing MI into two blocks, which are joined by
886 /// an unconditional branch.  Update data structures and renumber blocks to
887 /// account for this change and returns the newly created block.
888 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
889   MachineBasicBlock *OrigBB = MI->getParent();
890 
891   // Collect liveness information at MI.
892   LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());
893   LRs.addLiveOuts(*OrigBB);
894   auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();
895   for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))
896     LRs.stepBackward(LiveMI);
897 
898   // Create a new MBB for the code after the OrigBB.
899   MachineBasicBlock *NewBB =
900     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
901   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
902   MF->insert(MBBI, NewBB);
903 
904   // Splice the instructions starting with MI over to NewBB.
905   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
906 
907   // Add an unconditional branch from OrigBB to NewBB.
908   // Note the new unconditional branch is not being recorded.
909   // There doesn't seem to be meaningful DebugInfo available; this doesn't
910   // correspond to anything in the source.
911   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
912   if (!isThumb)
913     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
914   else
915     BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
916         .addMBB(NewBB)
917         .add(predOps(ARMCC::AL));
918   ++NumSplit;
919 
920   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
921   NewBB->transferSuccessors(OrigBB);
922 
923   // OrigBB branches to NewBB.
924   OrigBB->addSuccessor(NewBB);
925 
926   // Update live-in information in the new block.
927   MachineRegisterInfo &MRI = MF->getRegInfo();
928   for (MCPhysReg L : LRs)
929     if (!MRI.isReserved(L))
930       NewBB->addLiveIn(L);
931 
932   // Update internal data structures to account for the newly inserted MBB.
933   // This is almost the same as updateForInsertedWaterBlock, except that
934   // the Water goes after OrigBB, not NewBB.
935   MF->RenumberBlocks(NewBB);
936 
937   // Insert an entry into BBInfo to align it properly with the (newly
938   // renumbered) block numbers.
939   BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
940 
941   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
942   // available water after it (but not if it's already there, which happens
943   // when splitting before a conditional branch that is followed by an
944   // unconditional branch - in that case we want to insert NewBB).
945   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
946   MachineBasicBlock* WaterBB = *IP;
947   if (WaterBB == OrigBB)
948     WaterList.insert(std::next(IP), NewBB);
949   else
950     WaterList.insert(IP, OrigBB);
951   NewWaterList.insert(OrigBB);
952 
953   // Figure out how large the OrigBB is.  As the first half of the original
954   // block, it cannot contain a tablejump.  The size includes
955   // the new jump we added.  (It should be possible to do this without
956   // recounting everything, but it's very confusing, and this is rarely
957   // executed.)
958   BBUtils->computeBlockSize(OrigBB);
959 
960   // Figure out how large the NewMBB is.  As the second half of the original
961   // block, it may contain a tablejump.
962   BBUtils->computeBlockSize(NewBB);
963 
964   // All BBOffsets following these blocks must be modified.
965   BBUtils->adjustBBOffsetsAfter(OrigBB);
966 
967   return NewBB;
968 }
969 
970 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
971 /// displacement computation.  Update U.KnownAlignment to match its current
972 /// basic block location.
973 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
974   unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
975 
976   SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
977   const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
978   unsigned KnownBits = BBI.internalKnownBits();
979 
980   // The value read from PC is offset from the actual instruction address.
981   UserOffset += (isThumb ? 4 : 8);
982 
983   // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
984   // Make sure U.getMaxDisp() returns a constrained range.
985   U.KnownAlignment = (KnownBits >= 2);
986 
987   // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
988   // purposes of the displacement computation; compensate for that here.
989   // For unknown alignments, getMaxDisp() constrains the range instead.
990   if (isThumb && U.KnownAlignment)
991     UserOffset &= ~3u;
992 
993   return UserOffset;
994 }
995 
996 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
997 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
998 /// constant pool entry).
999 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
1000 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1001 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
1002 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
1003                                          unsigned TrialOffset, unsigned MaxDisp,
1004                                          bool NegativeOK, bool IsSoImm) {
1005   if (UserOffset <= TrialOffset) {
1006     // User before the Trial.
1007     if (TrialOffset - UserOffset <= MaxDisp)
1008       return true;
1009     // FIXME: Make use full range of soimm values.
1010   } else if (NegativeOK) {
1011     if (UserOffset - TrialOffset <= MaxDisp)
1012       return true;
1013     // FIXME: Make use full range of soimm values.
1014   }
1015   return false;
1016 }
1017 
1018 /// isWaterInRange - Returns true if a CPE placed after the specified
1019 /// Water (a basic block) will be in range for the specific MI.
1020 ///
1021 /// Compute how much the function will grow by inserting a CPE after Water.
1022 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
1023                                         MachineBasicBlock* Water, CPUser &U,
1024                                         unsigned &Growth) {
1025   BBInfoVector &BBInfo = BBUtils->getBBInfo();
1026   unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1027   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1028   unsigned NextBlockOffset;
1029   llvm::Align NextBlockAlignment;
1030   MachineFunction::const_iterator NextBlock = Water->getIterator();
1031   if (++NextBlock == MF->end()) {
1032     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1033   } else {
1034     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1035     NextBlockAlignment = NextBlock->getAlignment();
1036   }
1037   unsigned Size = U.CPEMI->getOperand(2).getImm();
1038   unsigned CPEEnd = CPEOffset + Size;
1039 
1040   // The CPE may be able to hide in the alignment padding before the next
1041   // block. It may also cause more padding to be required if it is more aligned
1042   // that the next block.
1043   if (CPEEnd > NextBlockOffset) {
1044     Growth = CPEEnd - NextBlockOffset;
1045     // Compute the padding that would go at the end of the CPE to align the next
1046     // block.
1047     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
1048 
1049     // If the CPE is to be inserted before the instruction, that will raise
1050     // the offset of the instruction. Also account for unknown alignment padding
1051     // in blocks between CPE and the user.
1052     if (CPEOffset < UserOffset)
1053       UserOffset +=
1054           Growth + UnknownPadding(Log2(MF->getAlignment()), CPELogAlign);
1055   } else
1056     // CPE fits in existing padding.
1057     Growth = 0;
1058 
1059   return isOffsetInRange(UserOffset, CPEOffset, U);
1060 }
1061 
1062 /// isCPEntryInRange - Returns true if the distance between specific MI and
1063 /// specific ConstPool entry instruction can fit in MI's displacement field.
1064 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1065                                       MachineInstr *CPEMI, unsigned MaxDisp,
1066                                       bool NegOk, bool DoDump) {
1067   unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
1068 
1069   if (DoDump) {
1070     LLVM_DEBUG({
1071         BBInfoVector &BBInfo = BBUtils->getBBInfo();
1072       unsigned Block = MI->getParent()->getNumber();
1073       const BasicBlockInfo &BBI = BBInfo[Block];
1074       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1075              << " max delta=" << MaxDisp
1076              << format(" insn address=%#x", UserOffset) << " in "
1077              << printMBBReference(*MI->getParent()) << ": "
1078              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1079              << format("CPE address=%#x offset=%+d: ", CPEOffset,
1080                        int(CPEOffset - UserOffset));
1081     });
1082   }
1083 
1084   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1085 }
1086 
1087 #ifndef NDEBUG
1088 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1089 /// unconditionally branches to its only successor.
1090 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1091   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1092     return false;
1093 
1094   MachineBasicBlock *Succ = *MBB->succ_begin();
1095   MachineBasicBlock *Pred = *MBB->pred_begin();
1096   MachineInstr *PredMI = &Pred->back();
1097   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1098       || PredMI->getOpcode() == ARM::t2B)
1099     return PredMI->getOperand(0).getMBB() == Succ;
1100   return false;
1101 }
1102 #endif // NDEBUG
1103 
1104 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1105 /// and instruction CPEMI, and decrement its refcount.  If the refcount
1106 /// becomes 0 remove the entry and instruction.  Returns true if we removed
1107 /// the entry, false if we didn't.
1108 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1109                                                     MachineInstr *CPEMI) {
1110   // Find the old entry. Eliminate it if it is no longer used.
1111   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1112   assert(CPE && "Unexpected!");
1113   if (--CPE->RefCount == 0) {
1114     removeDeadCPEMI(CPEMI);
1115     CPE->CPEMI = nullptr;
1116     --NumCPEs;
1117     return true;
1118   }
1119   return false;
1120 }
1121 
1122 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1123   if (CPEMI->getOperand(1).isCPI())
1124     return CPEMI->getOperand(1).getIndex();
1125 
1126   return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1127 }
1128 
1129 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1130 /// if not, see if an in-range clone of the CPE is in range, and if so,
1131 /// change the data structures so the user references the clone.  Returns:
1132 /// 0 = no existing entry found
1133 /// 1 = entry found, and there were no code insertions or deletions
1134 /// 2 = entry found, and there were code insertions or deletions
1135 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
1136   MachineInstr *UserMI = U.MI;
1137   MachineInstr *CPEMI  = U.CPEMI;
1138 
1139   // Check to see if the CPE is already in-range.
1140   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1141                        true)) {
1142     LLVM_DEBUG(dbgs() << "In range\n");
1143     return 1;
1144   }
1145 
1146   // No.  Look for previously created clones of the CPE that are in range.
1147   unsigned CPI = getCombinedIndex(CPEMI);
1148   std::vector<CPEntry> &CPEs = CPEntries[CPI];
1149   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1150     // We already tried this one
1151     if (CPEs[i].CPEMI == CPEMI)
1152       continue;
1153     // Removing CPEs can leave empty entries, skip
1154     if (CPEs[i].CPEMI == nullptr)
1155       continue;
1156     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1157                      U.NegOk)) {
1158       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1159                         << CPEs[i].CPI << "\n");
1160       // Point the CPUser node to the replacement
1161       U.CPEMI = CPEs[i].CPEMI;
1162       // Change the CPI in the instruction operand to refer to the clone.
1163       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1164         if (UserMI->getOperand(j).isCPI()) {
1165           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1166           break;
1167         }
1168       // Adjust the refcount of the clone...
1169       CPEs[i].RefCount++;
1170       // ...and the original.  If we didn't remove the old entry, none of the
1171       // addresses changed, so we don't need another pass.
1172       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1173     }
1174   }
1175   return 0;
1176 }
1177 
1178 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1179 /// the specific unconditional branch instruction.
1180 static inline unsigned getUnconditionalBrDisp(int Opc) {
1181   switch (Opc) {
1182   case ARM::tB:
1183     return ((1<<10)-1)*2;
1184   case ARM::t2B:
1185     return ((1<<23)-1)*2;
1186   default:
1187     break;
1188   }
1189 
1190   return ((1<<23)-1)*4;
1191 }
1192 
1193 /// findAvailableWater - Look for an existing entry in the WaterList in which
1194 /// we can place the CPE referenced from U so it's within range of U's MI.
1195 /// Returns true if found, false if not.  If it returns true, WaterIter
1196 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1197 /// introduce padding to water that will.  To ensure that this pass
1198 /// terminates, the CPE location for a particular CPUser is only allowed to
1199 /// move to a lower address, so search backward from the end of the list and
1200 /// prefer the first water that is in range.
1201 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1202                                             water_iterator &WaterIter,
1203                                             bool CloserWater) {
1204   if (WaterList.empty())
1205     return false;
1206 
1207   unsigned BestGrowth = ~0u;
1208   // The nearest water without splitting the UserBB is right after it.
1209   // If the distance is still large (we have a big BB), then we need to split it
1210   // if we don't converge after certain iterations. This helps the following
1211   // situation to converge:
1212   //   BB0:
1213   //      Big BB
1214   //   BB1:
1215   //      Constant Pool
1216   // When a CP access is out of range, BB0 may be used as water. However,
1217   // inserting islands between BB0 and BB1 makes other accesses out of range.
1218   MachineBasicBlock *UserBB = U.MI->getParent();
1219   BBInfoVector &BBInfo = BBUtils->getBBInfo();
1220   unsigned MinNoSplitDisp =
1221       BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1222   if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1223     return false;
1224   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1225        --IP) {
1226     MachineBasicBlock* WaterBB = *IP;
1227     // Check if water is in range and is either at a lower address than the
1228     // current "high water mark" or a new water block that was created since
1229     // the previous iteration by inserting an unconditional branch.  In the
1230     // latter case, we want to allow resetting the high water mark back to
1231     // this new water since we haven't seen it before.  Inserting branches
1232     // should be relatively uncommon and when it does happen, we want to be
1233     // sure to take advantage of it for all the CPEs near that block, so that
1234     // we don't insert more branches than necessary.
1235     // When CloserWater is true, we try to find the lowest address after (or
1236     // equal to) user MI's BB no matter of padding growth.
1237     unsigned Growth;
1238     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1239         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1240          NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1241         Growth < BestGrowth) {
1242       // This is the least amount of required padding seen so far.
1243       BestGrowth = Growth;
1244       WaterIter = IP;
1245       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1246                         << " Growth=" << Growth << '\n');
1247 
1248       if (CloserWater && WaterBB == U.MI->getParent())
1249         return true;
1250       // Keep looking unless it is perfect and we're not looking for the lowest
1251       // possible address.
1252       if (!CloserWater && BestGrowth == 0)
1253         return true;
1254     }
1255     if (IP == B)
1256       break;
1257   }
1258   return BestGrowth != ~0u;
1259 }
1260 
1261 /// createNewWater - No existing WaterList entry will work for
1262 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1263 /// block is used if in range, and the conditional branch munged so control
1264 /// flow is correct.  Otherwise the block is split to create a hole with an
1265 /// unconditional branch around it.  In either case NewMBB is set to a
1266 /// block following which the new island can be inserted (the WaterList
1267 /// is not adjusted).
1268 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1269                                         unsigned UserOffset,
1270                                         MachineBasicBlock *&NewMBB) {
1271   CPUser &U = CPUsers[CPUserIndex];
1272   MachineInstr *UserMI = U.MI;
1273   MachineInstr *CPEMI  = U.CPEMI;
1274   unsigned CPELogAlign = getCPELogAlign(CPEMI);
1275   MachineBasicBlock *UserMBB = UserMI->getParent();
1276   BBInfoVector &BBInfo = BBUtils->getBBInfo();
1277   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1278 
1279   // If the block does not end in an unconditional branch already, and if the
1280   // end of the block is within range, make new water there.  (The addition
1281   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1282   // Thumb2, 2 on Thumb1.
1283   if (BBHasFallthrough(UserMBB)) {
1284     // Size of branch to insert.
1285     unsigned Delta = isThumb1 ? 2 : 4;
1286     // Compute the offset where the CPE will begin.
1287     unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1288 
1289     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1290       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1291                         << format(", expected CPE offset %#x\n", CPEOffset));
1292       NewMBB = &*++UserMBB->getIterator();
1293       // Add an unconditional branch from UserMBB to fallthrough block.  Record
1294       // it for branch lengthening; this new branch will not get out of range,
1295       // but if the preceding conditional branch is out of range, the targets
1296       // will be exchanged, and the altered branch may be out of range, so the
1297       // machinery has to know about it.
1298       int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1299       if (!isThumb)
1300         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1301       else
1302         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1303             .addMBB(NewMBB)
1304             .add(predOps(ARMCC::AL));
1305       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1306       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1307                                       MaxDisp, false, UncondBr));
1308       BBUtils->computeBlockSize(UserMBB);
1309       BBUtils->adjustBBOffsetsAfter(UserMBB);
1310       return;
1311     }
1312   }
1313 
1314   // What a big block.  Find a place within the block to split it.  This is a
1315   // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1316   // entries are 4 bytes: if instruction I references island CPE, and
1317   // instruction I+1 references CPE', it will not work well to put CPE as far
1318   // forward as possible, since then CPE' cannot immediately follow it (that
1319   // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1320   // need to create a new island.  So, we make a first guess, then walk through
1321   // the instructions between the one currently being looked at and the
1322   // possible insertion point, and make sure any other instructions that
1323   // reference CPEs will be able to use the same island area; if not, we back
1324   // up the insertion point.
1325 
1326   // Try to split the block so it's fully aligned.  Compute the latest split
1327   // point where we can add a 4-byte branch instruction, and then align to
1328   // LogAlign which is the largest possible alignment in the function.
1329   unsigned LogAlign = Log2(MF->getAlignment());
1330   assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1331   unsigned KnownBits = UserBBI.internalKnownBits();
1332   unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1333   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1334   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1335                               BaseInsertOffset));
1336 
1337   // The 4 in the following is for the unconditional branch we'll be inserting
1338   // (allows for long branch on Thumb1).  Alignment of the island is handled
1339   // inside isOffsetInRange.
1340   BaseInsertOffset -= 4;
1341 
1342   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1343                     << " la=" << LogAlign << " kb=" << KnownBits
1344                     << " up=" << UPad << '\n');
1345 
1346   // This could point off the end of the block if we've already got constant
1347   // pool entries following this block; only the last one is in the water list.
1348   // Back past any possible branches (allow for a conditional and a maximally
1349   // long unconditional).
1350   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1351     // Ensure BaseInsertOffset is larger than the offset of the instruction
1352     // following UserMI so that the loop which searches for the split point
1353     // iterates at least once.
1354     BaseInsertOffset =
1355         std::max(UserBBI.postOffset() - UPad - 8,
1356                  UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
1357     // If the CP is referenced(ie, UserOffset) is in first four instructions
1358     // after IT, this recalculated BaseInsertOffset could be in the middle of
1359     // an IT block. If it is, change the BaseInsertOffset to just after the
1360     // IT block. This still make the CP Entry is in range becuase of the
1361     // following reasons.
1362     //   1. The initial BaseseInsertOffset calculated is (UserOffset +
1363     //   U.getMaxDisp() - UPad).
1364     //   2. An IT block is only at most 4 instructions plus the "it" itself (18
1365     //   bytes).
1366     //   3. All the relevant instructions support much larger Maximum
1367     //   displacement.
1368     MachineBasicBlock::iterator I = UserMI;
1369     ++I;
1370     for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI),
1371                   PredReg = 0;
1372          I->getOpcode() != ARM::t2IT &&
1373          getITInstrPredicate(*I, PredReg) != ARMCC::AL;
1374          Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {
1375       BaseInsertOffset =
1376           std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);
1377       assert(I != UserMBB->end() && "Fell off end of block");
1378     }
1379     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1380   }
1381   unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1382     CPEMI->getOperand(2).getImm();
1383   MachineBasicBlock::iterator MI = UserMI;
1384   ++MI;
1385   unsigned CPUIndex = CPUserIndex+1;
1386   unsigned NumCPUsers = CPUsers.size();
1387   MachineInstr *LastIT = nullptr;
1388   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1389        Offset < BaseInsertOffset;
1390        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1391     assert(MI != UserMBB->end() && "Fell off end of block");
1392     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
1393       CPUser &U = CPUsers[CPUIndex];
1394       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1395         // Shift intertion point by one unit of alignment so it is within reach.
1396         BaseInsertOffset -= 1u << LogAlign;
1397         EndInsertOffset  -= 1u << LogAlign;
1398       }
1399       // This is overly conservative, as we don't account for CPEMIs being
1400       // reused within the block, but it doesn't matter much.  Also assume CPEs
1401       // are added in order with alignment padding.  We may eventually be able
1402       // to pack the aligned CPEs better.
1403       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1404       CPUIndex++;
1405     }
1406 
1407     // Remember the last IT instruction.
1408     if (MI->getOpcode() == ARM::t2IT)
1409       LastIT = &*MI;
1410   }
1411 
1412   --MI;
1413 
1414   // Avoid splitting an IT block.
1415   if (LastIT) {
1416     unsigned PredReg = 0;
1417     ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
1418     if (CC != ARMCC::AL)
1419       MI = LastIT;
1420   }
1421 
1422   // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1423   // On Windows, this instruction pair is covered by one single
1424   // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1425   // constant island is injected inbetween them, the relocation will clobber
1426   // the instruction and fail to update the MOVT instruction.
1427   // (These instructions are bundled up until right before the ConstantIslands
1428   // pass.)
1429   if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
1430       (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1431           ARMII::MO_HI16) {
1432     --MI;
1433     assert(MI->getOpcode() == ARM::t2MOVi16 &&
1434            (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1435                ARMII::MO_LO16);
1436   }
1437 
1438   // We really must not split an IT block.
1439 #ifndef NDEBUG
1440   unsigned PredReg;
1441   assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);
1442 #endif
1443   NewMBB = splitBlockBeforeInstr(&*MI);
1444 }
1445 
1446 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1447 /// is out-of-range.  If so, pick up the constant pool value and move it some
1448 /// place in-range.  Return true if we changed any addresses (thus must run
1449 /// another pass of branch lengthening), false otherwise.
1450 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1451                                                 bool CloserWater) {
1452   CPUser &U = CPUsers[CPUserIndex];
1453   MachineInstr *UserMI = U.MI;
1454   MachineInstr *CPEMI  = U.CPEMI;
1455   unsigned CPI = getCombinedIndex(CPEMI);
1456   unsigned Size = CPEMI->getOperand(2).getImm();
1457   // Compute this only once, it's expensive.
1458   unsigned UserOffset = getUserOffset(U);
1459 
1460   // See if the current entry is within range, or there is a clone of it
1461   // in range.
1462   int result = findInRangeCPEntry(U, UserOffset);
1463   if (result==1) return false;
1464   else if (result==2) return true;
1465 
1466   // No existing clone of this CPE is within range.
1467   // We will be generating a new clone.  Get a UID for it.
1468   unsigned ID = AFI->createPICLabelUId();
1469 
1470   // Look for water where we can place this CPE.
1471   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1472   MachineBasicBlock *NewMBB;
1473   water_iterator IP;
1474   if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
1475     LLVM_DEBUG(dbgs() << "Found water in range\n");
1476     MachineBasicBlock *WaterBB = *IP;
1477 
1478     // If the original WaterList entry was "new water" on this iteration,
1479     // propagate that to the new island.  This is just keeping NewWaterList
1480     // updated to match the WaterList, which will be updated below.
1481     if (NewWaterList.erase(WaterBB))
1482       NewWaterList.insert(NewIsland);
1483 
1484     // The new CPE goes before the following block (NewMBB).
1485     NewMBB = &*++WaterBB->getIterator();
1486   } else {
1487     // No water found.
1488     LLVM_DEBUG(dbgs() << "No water found\n");
1489     createNewWater(CPUserIndex, UserOffset, NewMBB);
1490 
1491     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1492     // called while handling branches so that the water will be seen on the
1493     // next iteration for constant pools, but in this context, we don't want
1494     // it.  Check for this so it will be removed from the WaterList.
1495     // Also remove any entry from NewWaterList.
1496     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1497     IP = find(WaterList, WaterBB);
1498     if (IP != WaterList.end())
1499       NewWaterList.erase(WaterBB);
1500 
1501     // We are adding new water.  Update NewWaterList.
1502     NewWaterList.insert(NewIsland);
1503   }
1504   // Always align the new block because CP entries can be smaller than 4
1505   // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1506   // be an already aligned constant pool block.
1507   const unsigned LogAlign = isThumb ? 1 : 2;
1508   if (NewMBB->getLogAlignment() < LogAlign)
1509     NewMBB->setLogAlignment(LogAlign);
1510 
1511   // Remove the original WaterList entry; we want subsequent insertions in
1512   // this vicinity to go after the one we're about to insert.  This
1513   // considerably reduces the number of times we have to move the same CPE
1514   // more than once and is also important to ensure the algorithm terminates.
1515   if (IP != WaterList.end())
1516     WaterList.erase(IP);
1517 
1518   // Okay, we know we can put an island before NewMBB now, do it!
1519   MF->insert(NewMBB->getIterator(), NewIsland);
1520 
1521   // Update internal data structures to account for the newly inserted MBB.
1522   updateForInsertedWaterBlock(NewIsland);
1523 
1524   // Now that we have an island to add the CPE to, clone the original CPE and
1525   // add it to the island.
1526   U.HighWaterMark = NewIsland;
1527   U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1528                 .addImm(ID)
1529                 .add(CPEMI->getOperand(1))
1530                 .addImm(Size);
1531   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1532   ++NumCPEs;
1533 
1534   // Decrement the old entry, and remove it if refcount becomes 0.
1535   decrementCPEReferenceCount(CPI, CPEMI);
1536 
1537   // Mark the basic block as aligned as required by the const-pool entry.
1538   NewIsland->setLogAlignment(getCPELogAlign(U.CPEMI));
1539 
1540   // Increase the size of the island block to account for the new entry.
1541   BBUtils->adjustBBSize(NewIsland, Size);
1542   BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1543 
1544   // Finally, change the CPI in the instruction operand to be ID.
1545   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1546     if (UserMI->getOperand(i).isCPI()) {
1547       UserMI->getOperand(i).setIndex(ID);
1548       break;
1549     }
1550 
1551   LLVM_DEBUG(
1552       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1553              << format(" offset=%#x\n",
1554                        BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
1555 
1556   return true;
1557 }
1558 
1559 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1560 /// sizes and offsets of impacted basic blocks.
1561 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1562   MachineBasicBlock *CPEBB = CPEMI->getParent();
1563   unsigned Size = CPEMI->getOperand(2).getImm();
1564   CPEMI->eraseFromParent();
1565   BBInfoVector &BBInfo = BBUtils->getBBInfo();
1566   BBUtils->adjustBBSize(CPEBB, -Size);
1567   // All succeeding offsets have the current size value added in, fix this.
1568   if (CPEBB->empty()) {
1569     BBInfo[CPEBB->getNumber()].Size = 0;
1570 
1571     // This block no longer needs to be aligned.
1572     CPEBB->setLogAlignment(0);
1573   } else
1574     // Entries are sorted by descending alignment, so realign from the front.
1575     CPEBB->setLogAlignment(getCPELogAlign(&*CPEBB->begin()));
1576 
1577   BBUtils->adjustBBOffsetsAfter(CPEBB);
1578   // An island has only one predecessor BB and one successor BB. Check if
1579   // this BB's predecessor jumps directly to this BB's successor. This
1580   // shouldn't happen currently.
1581   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1582   // FIXME: remove the empty blocks after all the work is done?
1583 }
1584 
1585 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1586 /// are zero.
1587 bool ARMConstantIslands::removeUnusedCPEntries() {
1588   unsigned MadeChange = false;
1589   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1590       std::vector<CPEntry> &CPEs = CPEntries[i];
1591       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1592         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1593           removeDeadCPEMI(CPEs[j].CPEMI);
1594           CPEs[j].CPEMI = nullptr;
1595           MadeChange = true;
1596         }
1597       }
1598   }
1599   return MadeChange;
1600 }
1601 
1602 
1603 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1604 /// away to fit in its displacement field.
1605 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1606   MachineInstr *MI = Br.MI;
1607   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1608 
1609   // Check to see if the DestBB is already in-range.
1610   if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
1611     return false;
1612 
1613   if (!Br.isCond)
1614     return fixupUnconditionalBr(Br);
1615   return fixupConditionalBr(Br);
1616 }
1617 
1618 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1619 /// too far away to fit in its displacement field. If the LR register has been
1620 /// spilled in the epilogue, then we can use BL to implement a far jump.
1621 /// Otherwise, add an intermediate branch instruction to a branch.
1622 bool
1623 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1624   MachineInstr *MI = Br.MI;
1625   MachineBasicBlock *MBB = MI->getParent();
1626   if (!isThumb1)
1627     llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1628 
1629   if (!AFI->isLRSpilled())
1630     report_fatal_error("underestimated function size");
1631 
1632   // Use BL to implement far jump.
1633   Br.MaxDisp = (1 << 21) * 2;
1634   MI->setDesc(TII->get(ARM::tBfar));
1635   BBInfoVector &BBInfo = BBUtils->getBBInfo();
1636   BBInfo[MBB->getNumber()].Size += 2;
1637   BBUtils->adjustBBOffsetsAfter(MBB);
1638   HasFarJump = true;
1639   ++NumUBrFixed;
1640 
1641   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1642 
1643   return true;
1644 }
1645 
1646 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1647 /// far away to fit in its displacement field. It is converted to an inverse
1648 /// conditional branch + an unconditional branch to the destination.
1649 bool
1650 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1651   MachineInstr *MI = Br.MI;
1652   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1653 
1654   // Add an unconditional branch to the destination and invert the branch
1655   // condition to jump over it:
1656   // blt L1
1657   // =>
1658   // bge L2
1659   // b   L1
1660   // L2:
1661   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1662   CC = ARMCC::getOppositeCondition(CC);
1663   Register CCReg = MI->getOperand(2).getReg();
1664 
1665   // If the branch is at the end of its MBB and that has a fall-through block,
1666   // direct the updated conditional branch to the fall-through block. Otherwise,
1667   // split the MBB before the next instruction.
1668   MachineBasicBlock *MBB = MI->getParent();
1669   MachineInstr *BMI = &MBB->back();
1670   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1671 
1672   ++NumCBrFixed;
1673   if (BMI != MI) {
1674     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1675         BMI->getOpcode() == Br.UncondBr) {
1676       // Last MI in the BB is an unconditional branch. Can we simply invert the
1677       // condition and swap destinations:
1678       // beq L1
1679       // b   L2
1680       // =>
1681       // bne L2
1682       // b   L1
1683       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1684       if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
1685         LLVM_DEBUG(
1686             dbgs() << "  Invert Bcc condition and swap its destination with "
1687                    << *BMI);
1688         BMI->getOperand(0).setMBB(DestBB);
1689         MI->getOperand(0).setMBB(NewDest);
1690         MI->getOperand(1).setImm(CC);
1691         return true;
1692       }
1693     }
1694   }
1695 
1696   if (NeedSplit) {
1697     splitBlockBeforeInstr(MI);
1698     // No need for the branch to the next block. We're adding an unconditional
1699     // branch to the destination.
1700     int delta = TII->getInstSizeInBytes(MBB->back());
1701     BBUtils->adjustBBSize(MBB, -delta);
1702     MBB->back().eraseFromParent();
1703 
1704     // The conditional successor will be swapped between the BBs after this, so
1705     // update CFG.
1706     MBB->addSuccessor(DestBB);
1707     std::next(MBB->getIterator())->removeSuccessor(DestBB);
1708 
1709     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1710   }
1711   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1712 
1713   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1714                     << " also invert condition and change dest. to "
1715                     << printMBBReference(*NextBB) << "\n");
1716 
1717   // Insert a new conditional branch and a new unconditional branch.
1718   // Also update the ImmBranch as well as adding a new entry for the new branch.
1719   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1720     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1721   Br.MI = &MBB->back();
1722   BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
1723   if (isThumb)
1724     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1725         .addMBB(DestBB)
1726         .add(predOps(ARMCC::AL));
1727   else
1728     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1729   BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
1730   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1731   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1732 
1733   // Remove the old conditional branch.  It may or may not still be in MBB.
1734   BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
1735   MI->eraseFromParent();
1736   BBUtils->adjustBBOffsetsAfter(MBB);
1737   return true;
1738 }
1739 
1740 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1741 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1742 /// to do this if tBfar is not used.
1743 bool ARMConstantIslands::undoLRSpillRestore() {
1744   bool MadeChange = false;
1745   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1746     MachineInstr *MI = PushPopMIs[i];
1747     // First two operands are predicates.
1748     if (MI->getOpcode() == ARM::tPOP_RET &&
1749         MI->getOperand(2).getReg() == ARM::PC &&
1750         MI->getNumExplicitOperands() == 3) {
1751       // Create the new insn and copy the predicate from the old.
1752       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1753           .add(MI->getOperand(0))
1754           .add(MI->getOperand(1));
1755       MI->eraseFromParent();
1756       MadeChange = true;
1757     } else if (MI->getOpcode() == ARM::tPUSH &&
1758                MI->getOperand(2).getReg() == ARM::LR &&
1759                MI->getNumExplicitOperands() == 3) {
1760       // Just remove the push.
1761       MI->eraseFromParent();
1762       MadeChange = true;
1763     }
1764   }
1765   return MadeChange;
1766 }
1767 
1768 bool ARMConstantIslands::optimizeThumb2Instructions() {
1769   bool MadeChange = false;
1770 
1771   // Shrink ADR and LDR from constantpool.
1772   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1773     CPUser &U = CPUsers[i];
1774     unsigned Opcode = U.MI->getOpcode();
1775     unsigned NewOpc = 0;
1776     unsigned Scale = 1;
1777     unsigned Bits = 0;
1778     switch (Opcode) {
1779     default: break;
1780     case ARM::t2LEApcrel:
1781       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1782         NewOpc = ARM::tLEApcrel;
1783         Bits = 8;
1784         Scale = 4;
1785       }
1786       break;
1787     case ARM::t2LDRpci:
1788       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1789         NewOpc = ARM::tLDRpci;
1790         Bits = 8;
1791         Scale = 4;
1792       }
1793       break;
1794     }
1795 
1796     if (!NewOpc)
1797       continue;
1798 
1799     unsigned UserOffset = getUserOffset(U);
1800     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1801 
1802     // Be conservative with inline asm.
1803     if (!U.KnownAlignment)
1804       MaxOffs -= 2;
1805 
1806     // FIXME: Check if offset is multiple of scale if scale is not 4.
1807     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1808       LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
1809       U.MI->setDesc(TII->get(NewOpc));
1810       MachineBasicBlock *MBB = U.MI->getParent();
1811       BBUtils->adjustBBSize(MBB, -2);
1812       BBUtils->adjustBBOffsetsAfter(MBB);
1813       ++NumT2CPShrunk;
1814       MadeChange = true;
1815     }
1816   }
1817 
1818   return MadeChange;
1819 }
1820 
1821 
1822 bool ARMConstantIslands::optimizeThumb2Branches() {
1823 
1824   auto TryShrinkBranch = [this](ImmBranch &Br) {
1825     unsigned Opcode = Br.MI->getOpcode();
1826     unsigned NewOpc = 0;
1827     unsigned Scale = 1;
1828     unsigned Bits = 0;
1829     switch (Opcode) {
1830     default: break;
1831     case ARM::t2B:
1832       NewOpc = ARM::tB;
1833       Bits = 11;
1834       Scale = 2;
1835       break;
1836     case ARM::t2Bcc:
1837       NewOpc = ARM::tBcc;
1838       Bits = 8;
1839       Scale = 2;
1840       break;
1841     }
1842     if (NewOpc) {
1843       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1844       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1845       if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
1846         LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1847         Br.MI->setDesc(TII->get(NewOpc));
1848         MachineBasicBlock *MBB = Br.MI->getParent();
1849         BBUtils->adjustBBSize(MBB, -2);
1850         BBUtils->adjustBBOffsetsAfter(MBB);
1851         ++NumT2BrShrunk;
1852         return true;
1853       }
1854     }
1855     return false;
1856   };
1857 
1858   struct ImmCompare {
1859     MachineInstr* MI = nullptr;
1860     unsigned NewOpc = 0;
1861   };
1862 
1863   auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,
1864                               MachineBasicBlock *DestBB) {
1865     ImmCmp.MI = nullptr;
1866     ImmCmp.NewOpc = 0;
1867 
1868     // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1869     // so this transformation is not safe.
1870     if (!Br.MI->killsRegister(ARM::CPSR))
1871       return false;
1872 
1873     unsigned PredReg = 0;
1874     unsigned NewOpc = 0;
1875     ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
1876     if (Pred == ARMCC::EQ)
1877       NewOpc = ARM::tCBZ;
1878     else if (Pred == ARMCC::NE)
1879       NewOpc = ARM::tCBNZ;
1880     else
1881       return false;
1882 
1883     // Check if the distance is within 126. Subtract starting offset by 2
1884     // because the cmp will be eliminated.
1885     unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
1886     BBInfoVector &BBInfo = BBUtils->getBBInfo();
1887     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1888     if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
1889       return false;
1890 
1891     // Search backwards to find a tCMPi8
1892     auto *TRI = STI->getRegisterInfo();
1893     MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
1894     if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
1895       return false;
1896 
1897     ImmCmp.MI = CmpMI;
1898     ImmCmp.NewOpc = NewOpc;
1899     return true;
1900   };
1901 
1902   auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {
1903     if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() ||
1904         STI->hasMinSize())
1905       return false;
1906 
1907     MachineBasicBlock *MBB = Br.MI->getParent();
1908     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1909     if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||
1910         !BBUtils->isBBInRange(Br.MI, DestBB, 4094))
1911       return false;
1912 
1913     if (!DT->dominates(DestBB, MBB))
1914       return false;
1915 
1916     // We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite
1917     // target of Br. So now we need to reverse the condition.
1918     Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;
1919 
1920     MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),
1921                                       TII->get(ARM::t2LE));
1922     MIB.add(Br.MI->getOperand(0));
1923     Br.MI->eraseFromParent();
1924     Br.MI = MIB;
1925     ++NumLEInserted;
1926     return true;
1927   };
1928 
1929   bool MadeChange = false;
1930 
1931   // The order in which branches appear in ImmBranches is approximately their
1932   // order within the function body. By visiting later branches first, we reduce
1933   // the distance between earlier forward branches and their targets, making it
1934   // more likely that the cbn?z optimization, which can only apply to forward
1935   // branches, will succeed.
1936   for (ImmBranch &Br : reverse(ImmBranches)) {
1937     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1938     MachineBasicBlock *MBB = Br.MI->getParent();
1939     MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?
1940       MBB->getFallThrough() :
1941       MBB->back().getOperand(0).getMBB();
1942 
1943     ImmCompare Cmp;
1944     if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {
1945       DestBB = ExitBB;
1946       MadeChange = true;
1947     } else {
1948       FindCmpForCBZ(Br, Cmp, DestBB);
1949       MadeChange |= TryShrinkBranch(Br);
1950     }
1951 
1952     unsigned Opcode = Br.MI->getOpcode();
1953     if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)
1954       continue;
1955 
1956     Register Reg = Cmp.MI->getOperand(0).getReg();
1957 
1958     // Check for Kill flags on Reg. If they are present remove them and set kill
1959     // on the new CBZ.
1960     auto *TRI = STI->getRegisterInfo();
1961     MachineBasicBlock::iterator KillMI = Br.MI;
1962     bool RegKilled = false;
1963     do {
1964       --KillMI;
1965       if (KillMI->killsRegister(Reg, TRI)) {
1966         KillMI->clearRegisterKills(Reg, TRI);
1967         RegKilled = true;
1968         break;
1969       }
1970     } while (KillMI != Cmp.MI);
1971 
1972     // Create the new CBZ/CBNZ
1973     LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);
1974     MachineInstr *NewBR =
1975         BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))
1976             .addReg(Reg, getKillRegState(RegKilled))
1977             .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1978 
1979     Cmp.MI->eraseFromParent();
1980     BBInfoVector &BBInfo = BBUtils->getBBInfo();
1981     BBInfo[MBB->getNumber()].Size -= 2;
1982 
1983     if (Br.MI->getOpcode() == ARM::tBcc) {
1984       Br.MI->eraseFromParent();
1985       Br.MI = NewBR;
1986     } else if (&MBB->back() != Br.MI) {
1987       // We've generated an LE and already erased the original conditional
1988       // branch. The CBN?Z is now used to branch to the other successor, so an
1989       // unconditional branch terminator is now redundant.
1990       MachineInstr *LastMI = &MBB->back();
1991       if (LastMI != Br.MI) {
1992         BBInfo[MBB->getNumber()].Size -= LastMI->getDesc().getSize();
1993         LastMI->eraseFromParent();
1994       }
1995     }
1996     BBUtils->adjustBBOffsetsAfter(MBB);
1997     ++NumCBZ;
1998     MadeChange = true;
1999   }
2000 
2001   return MadeChange;
2002 }
2003 
2004 static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
2005                               unsigned BaseReg) {
2006   if (I.getOpcode() != ARM::t2ADDrs)
2007     return false;
2008 
2009   if (I.getOperand(0).getReg() != EntryReg)
2010     return false;
2011 
2012   if (I.getOperand(1).getReg() != BaseReg)
2013     return false;
2014 
2015   // FIXME: what about CC and IdxReg?
2016   return true;
2017 }
2018 
2019 /// While trying to form a TBB/TBH instruction, we may (if the table
2020 /// doesn't immediately follow the BR_JT) need access to the start of the
2021 /// jump-table. We know one instruction that produces such a register; this
2022 /// function works out whether that definition can be preserved to the BR_JT,
2023 /// possibly by removing an intervening addition (which is usually needed to
2024 /// calculate the actual entry to jump to).
2025 bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
2026                                               MachineInstr *LEAMI,
2027                                               unsigned &DeadSize,
2028                                               bool &CanDeleteLEA,
2029                                               bool &BaseRegKill) {
2030   if (JumpMI->getParent() != LEAMI->getParent())
2031     return false;
2032 
2033   // Now we hope that we have at least these instructions in the basic block:
2034   //     BaseReg = t2LEA ...
2035   //     [...]
2036   //     EntryReg = t2ADDrs BaseReg, ...
2037   //     [...]
2038   //     t2BR_JT EntryReg
2039   //
2040   // We have to be very conservative about what we recognise here though. The
2041   // main perturbing factors to watch out for are:
2042   //    + Spills at any point in the chain: not direct problems but we would
2043   //      expect a blocking Def of the spilled register so in practice what we
2044   //      can do is limited.
2045   //    + EntryReg == BaseReg: this is the one situation we should allow a Def
2046   //      of BaseReg, but only if the t2ADDrs can be removed.
2047   //    + Some instruction other than t2ADDrs computing the entry. Not seen in
2048   //      the wild, but we should be careful.
2049   Register EntryReg = JumpMI->getOperand(0).getReg();
2050   Register BaseReg = LEAMI->getOperand(0).getReg();
2051 
2052   CanDeleteLEA = true;
2053   BaseRegKill = false;
2054   MachineInstr *RemovableAdd = nullptr;
2055   MachineBasicBlock::iterator I(LEAMI);
2056   for (++I; &*I != JumpMI; ++I) {
2057     if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2058       RemovableAdd = &*I;
2059       break;
2060     }
2061 
2062     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2063       const MachineOperand &MO = I->getOperand(K);
2064       if (!MO.isReg() || !MO.getReg())
2065         continue;
2066       if (MO.isDef() && MO.getReg() == BaseReg)
2067         return false;
2068       if (MO.isUse() && MO.getReg() == BaseReg) {
2069         BaseRegKill = BaseRegKill || MO.isKill();
2070         CanDeleteLEA = false;
2071       }
2072     }
2073   }
2074 
2075   if (!RemovableAdd)
2076     return true;
2077 
2078   // Check the add really is removable, and that nothing else in the block
2079   // clobbers BaseReg.
2080   for (++I; &*I != JumpMI; ++I) {
2081     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2082       const MachineOperand &MO = I->getOperand(K);
2083       if (!MO.isReg() || !MO.getReg())
2084         continue;
2085       if (MO.isDef() && MO.getReg() == BaseReg)
2086         return false;
2087       if (MO.isUse() && MO.getReg() == EntryReg)
2088         RemovableAdd = nullptr;
2089     }
2090   }
2091 
2092   if (RemovableAdd) {
2093     RemovableAdd->eraseFromParent();
2094     DeadSize += isThumb2 ? 4 : 2;
2095   } else if (BaseReg == EntryReg) {
2096     // The add wasn't removable, but clobbered the base for the TBB. So we can't
2097     // preserve it.
2098     return false;
2099   }
2100 
2101   // We reached the end of the block without seeing another definition of
2102   // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2103   // used in the TBB/TBH if necessary.
2104   return true;
2105 }
2106 
2107 /// Returns whether CPEMI is the first instruction in the block
2108 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2109 /// we can switch the first register to PC and usually remove the address
2110 /// calculation that preceded it.
2111 static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
2112   MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
2113   MachineFunction *MF = MBB->getParent();
2114   ++MBB;
2115 
2116   return MBB != MF->end() && MBB->begin() != MBB->end() &&
2117          &*MBB->begin() == CPEMI;
2118 }
2119 
2120 static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
2121                                          MachineInstr *JumpMI,
2122                                          unsigned &DeadSize) {
2123   // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2124   // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2125   // and is not clobbered / used.
2126   MachineInstr *RemovableAdd = nullptr;
2127   Register EntryReg = JumpMI->getOperand(0).getReg();
2128 
2129   // Find the last ADD to set EntryReg
2130   MachineBasicBlock::iterator I(LEAMI);
2131   for (++I; &*I != JumpMI; ++I) {
2132     if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2133       RemovableAdd = &*I;
2134   }
2135 
2136   if (!RemovableAdd)
2137     return;
2138 
2139   // Ensure EntryReg is not clobbered or used.
2140   MachineBasicBlock::iterator J(RemovableAdd);
2141   for (++J; &*J != JumpMI; ++J) {
2142     for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2143       const MachineOperand &MO = J->getOperand(K);
2144       if (!MO.isReg() || !MO.getReg())
2145         continue;
2146       if (MO.isDef() && MO.getReg() == EntryReg)
2147         return;
2148       if (MO.isUse() && MO.getReg() == EntryReg)
2149         return;
2150     }
2151   }
2152 
2153   LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
2154   RemovableAdd->eraseFromParent();
2155   DeadSize += 4;
2156 }
2157 
2158 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
2159 /// jumptables when it's possible.
2160 bool ARMConstantIslands::optimizeThumb2JumpTables() {
2161   bool MadeChange = false;
2162 
2163   // FIXME: After the tables are shrunk, can we get rid some of the
2164   // constantpool tables?
2165   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2166   if (!MJTI) return false;
2167 
2168   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2169   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2170     MachineInstr *MI = T2JumpTables[i];
2171     const MCInstrDesc &MCID = MI->getDesc();
2172     unsigned NumOps = MCID.getNumOperands();
2173     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2174     MachineOperand JTOP = MI->getOperand(JTOpIdx);
2175     unsigned JTI = JTOP.getIndex();
2176     assert(JTI < JT.size());
2177 
2178     bool ByteOk = true;
2179     bool HalfWordOk = true;
2180     unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
2181     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2182     BBInfoVector &BBInfo = BBUtils->getBBInfo();
2183     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2184       MachineBasicBlock *MBB = JTBBs[j];
2185       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
2186       // Negative offset is not ok. FIXME: We should change BB layout to make
2187       // sure all the branches are forward.
2188       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
2189         ByteOk = false;
2190       unsigned TBHLimit = ((1<<16)-1)*2;
2191       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
2192         HalfWordOk = false;
2193       if (!ByteOk && !HalfWordOk)
2194         break;
2195     }
2196 
2197     if (!ByteOk && !HalfWordOk)
2198       continue;
2199 
2200     CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2201     MachineBasicBlock *MBB = MI->getParent();
2202     if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2203       continue;
2204 
2205     unsigned DeadSize = 0;
2206     bool CanDeleteLEA = false;
2207     bool BaseRegKill = false;
2208 
2209     unsigned IdxReg = ~0U;
2210     bool IdxRegKill = true;
2211     if (isThumb2) {
2212       IdxReg = MI->getOperand(1).getReg();
2213       IdxRegKill = MI->getOperand(1).isKill();
2214 
2215       bool PreservedBaseReg =
2216         preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2217       if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2218         continue;
2219     } else {
2220       // We're in thumb-1 mode, so we must have something like:
2221       //   %idx = tLSLri %idx, 2
2222       //   %base = tLEApcrelJT
2223       //   %t = tLDRr %base, %idx
2224       Register BaseReg = User.MI->getOperand(0).getReg();
2225 
2226       if (User.MI->getIterator() == User.MI->getParent()->begin())
2227         continue;
2228       MachineInstr *Shift = User.MI->getPrevNode();
2229       if (Shift->getOpcode() != ARM::tLSLri ||
2230           Shift->getOperand(3).getImm() != 2 ||
2231           !Shift->getOperand(2).isKill())
2232         continue;
2233       IdxReg = Shift->getOperand(2).getReg();
2234       Register ShiftedIdxReg = Shift->getOperand(0).getReg();
2235 
2236       // It's important that IdxReg is live until the actual TBB/TBH. Most of
2237       // the range is checked later, but the LEA might still clobber it and not
2238       // actually get removed.
2239       if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2240         continue;
2241 
2242       MachineInstr *Load = User.MI->getNextNode();
2243       if (Load->getOpcode() != ARM::tLDRr)
2244         continue;
2245       if (Load->getOperand(1).getReg() != BaseReg ||
2246           Load->getOperand(2).getReg() != ShiftedIdxReg ||
2247           !Load->getOperand(2).isKill())
2248         continue;
2249 
2250       // If we're in PIC mode, there should be another ADD following.
2251       auto *TRI = STI->getRegisterInfo();
2252 
2253       // %base cannot be redefined after the load as it will appear before
2254       // TBB/TBH like:
2255       //      %base =
2256       //      %base =
2257       //      tBB %base, %idx
2258       if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2259         continue;
2260 
2261       if (isPositionIndependentOrROPI) {
2262         MachineInstr *Add = Load->getNextNode();
2263         if (Add->getOpcode() != ARM::tADDrr ||
2264             Add->getOperand(2).getReg() != BaseReg ||
2265             Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2266             !Add->getOperand(3).isKill())
2267           continue;
2268         if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2269           continue;
2270         if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2271           // IdxReg gets redefined in the middle of the sequence.
2272           continue;
2273         Add->eraseFromParent();
2274         DeadSize += 2;
2275       } else {
2276         if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2277           continue;
2278         if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2279           // IdxReg gets redefined in the middle of the sequence.
2280           continue;
2281       }
2282 
2283       // Now safe to delete the load and lsl. The LEA will be removed later.
2284       CanDeleteLEA = true;
2285       Shift->eraseFromParent();
2286       Load->eraseFromParent();
2287       DeadSize += 4;
2288     }
2289 
2290     LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
2291     MachineInstr *CPEMI = User.CPEMI;
2292     unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2293     if (!isThumb2)
2294       Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2295 
2296     MachineBasicBlock::iterator MI_JT = MI;
2297     MachineInstr *NewJTMI =
2298         BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
2299             .addReg(User.MI->getOperand(0).getReg(),
2300                     getKillRegState(BaseRegKill))
2301             .addReg(IdxReg, getKillRegState(IdxRegKill))
2302             .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2303             .addImm(CPEMI->getOperand(0).getImm());
2304     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
2305 
2306     unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2307     CPEMI->setDesc(TII->get(JTOpc));
2308 
2309     if (jumpTableFollowsTB(MI, User.CPEMI)) {
2310       NewJTMI->getOperand(0).setReg(ARM::PC);
2311       NewJTMI->getOperand(0).setIsKill(false);
2312 
2313       if (CanDeleteLEA) {
2314         if (isThumb2)
2315           RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2316 
2317         User.MI->eraseFromParent();
2318         DeadSize += isThumb2 ? 4 : 2;
2319 
2320         // The LEA was eliminated, the TBB instruction becomes the only new user
2321         // of the jump table.
2322         User.MI = NewJTMI;
2323         User.MaxDisp = 4;
2324         User.NegOk = false;
2325         User.IsSoImm = false;
2326         User.KnownAlignment = false;
2327       } else {
2328         // The LEA couldn't be eliminated, so we must add another CPUser to
2329         // record the TBB or TBH use.
2330         int CPEntryIdx = JumpTableEntryIndices[JTI];
2331         auto &CPEs = CPEntries[CPEntryIdx];
2332         auto Entry =
2333             find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
2334         ++Entry->RefCount;
2335         CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2336       }
2337     }
2338 
2339     unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2340     unsigned OrigSize = TII->getInstSizeInBytes(*MI);
2341     MI->eraseFromParent();
2342 
2343     int Delta = OrigSize - NewSize + DeadSize;
2344     BBInfo[MBB->getNumber()].Size -= Delta;
2345     BBUtils->adjustBBOffsetsAfter(MBB);
2346 
2347     ++NumTBs;
2348     MadeChange = true;
2349   }
2350 
2351   return MadeChange;
2352 }
2353 
2354 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2355 /// jump tables always branch forwards, since that's what tbb and tbh need.
2356 bool ARMConstantIslands::reorderThumb2JumpTables() {
2357   bool MadeChange = false;
2358 
2359   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2360   if (!MJTI) return false;
2361 
2362   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2363   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2364     MachineInstr *MI = T2JumpTables[i];
2365     const MCInstrDesc &MCID = MI->getDesc();
2366     unsigned NumOps = MCID.getNumOperands();
2367     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2368     MachineOperand JTOP = MI->getOperand(JTOpIdx);
2369     unsigned JTI = JTOP.getIndex();
2370     assert(JTI < JT.size());
2371 
2372     // We prefer if target blocks for the jump table come after the jump
2373     // instruction so we can use TB[BH]. Loop through the target blocks
2374     // and try to adjust them such that that's true.
2375     int JTNumber = MI->getParent()->getNumber();
2376     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2377     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2378       MachineBasicBlock *MBB = JTBBs[j];
2379       int DTNumber = MBB->getNumber();
2380 
2381       if (DTNumber < JTNumber) {
2382         // The destination precedes the switch. Try to move the block forward
2383         // so we have a positive offset.
2384         MachineBasicBlock *NewBB =
2385           adjustJTTargetBlockForward(MBB, MI->getParent());
2386         if (NewBB)
2387           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2388         MadeChange = true;
2389       }
2390     }
2391   }
2392 
2393   return MadeChange;
2394 }
2395 
2396 MachineBasicBlock *ARMConstantIslands::
2397 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2398   // If the destination block is terminated by an unconditional branch,
2399   // try to move it; otherwise, create a new block following the jump
2400   // table that branches back to the actual target. This is a very simple
2401   // heuristic. FIXME: We can definitely improve it.
2402   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2403   SmallVector<MachineOperand, 4> Cond;
2404   SmallVector<MachineOperand, 4> CondPrior;
2405   MachineFunction::iterator BBi = BB->getIterator();
2406   MachineFunction::iterator OldPrior = std::prev(BBi);
2407 
2408   // If the block terminator isn't analyzable, don't try to move the block
2409   bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
2410 
2411   // If the block ends in an unconditional branch, move it. The prior block
2412   // has to have an analyzable terminator for us to move this one. Be paranoid
2413   // and make sure we're not trying to move the entry block of the function.
2414   if (!B && Cond.empty() && BB != &MF->front() &&
2415       !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2416     BB->moveAfter(JTBB);
2417     OldPrior->updateTerminator();
2418     BB->updateTerminator();
2419     // Update numbering to account for the block being moved.
2420     MF->RenumberBlocks();
2421     ++NumJTMoved;
2422     return nullptr;
2423   }
2424 
2425   // Create a new MBB for the code after the jump BB.
2426   MachineBasicBlock *NewBB =
2427     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2428   MachineFunction::iterator MBBI = ++JTBB->getIterator();
2429   MF->insert(MBBI, NewBB);
2430 
2431   // Copy live-in information to new block.
2432   for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())
2433     NewBB->addLiveIn(RegMaskPair);
2434 
2435   // Add an unconditional branch from NewBB to BB.
2436   // There doesn't seem to be meaningful DebugInfo available; this doesn't
2437   // correspond directly to anything in the source.
2438   if (isThumb2)
2439     BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2440         .addMBB(BB)
2441         .add(predOps(ARMCC::AL));
2442   else
2443     BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2444         .addMBB(BB)
2445         .add(predOps(ARMCC::AL));
2446 
2447   // Update internal data structures to account for the newly inserted MBB.
2448   MF->RenumberBlocks(NewBB);
2449 
2450   // Update the CFG.
2451   NewBB->addSuccessor(BB);
2452   JTBB->replaceSuccessor(BB, NewBB);
2453 
2454   ++NumJTInserted;
2455   return NewBB;
2456 }
2457 
2458 /// createARMConstantIslandPass - returns an instance of the constpool
2459 /// island pass.
2460 FunctionPass *llvm::createARMConstantIslandPass() {
2461   return new ARMConstantIslands();
2462 }
2463 
2464 INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2465                 false, false)
2466