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